问题
I am getting data from some ajax operation, and trying to use javascript to do some conditional checks actually
so when i print the response from the ajax like
document.write(response)
result
[object Object]
when i print something like document.write(JSON.stringify(response))
result
{"status":"failed","login":["This field is required."],"password":["This field is required."]}
so above is the actual data i am getting what i am trying to do is
if(response.status === 'failed')
window.location.href = response.next;
else if ('login' in response && response['login']==["This field is required."])
{
$("#message").html(<p>Username is required</p>);
}
else if ('password' in response && response['password']==["This field is required."])
{
$("#message").html(<p>Password is required</p>);
}
But the &&
condition response['login']==["This field is required."]
is not working
so how to check the value of above type in javascript ?
Note: *New to javascript *
回答1:
Access the different properties of the response object using the dot operator.
response.login[0] === "This field is required."
Just to let you know what's going on here - you're getting back a json object. Properties in a json object can be access by simple using .PropertyName. Your login property is an array, and ou you want to access the first item in the array, so you use the [0] indexer. Lastly, you're comparing strings, so best practice in javascript is to use the === operator, which will compare type and value.
回答2:
Try this validation instead. It compares first position of login
array.
response['login'][0] == "This field is required."
回答3:
Because an array is not equal to another array. Check response['login'][0]
to compare the strings instead.
> var array1 = ['array'];
> array1 == ['array']
< false
> array1[0] == 'array'
< true
回答4:
remove []
. this is array. you must compare with string
回答5:
JSON
is basically a transportable format of Javascript syntax. You're comparing the wrong things. Once a JSON string is decode in Javascript, it becomes a NATIVE javascript object/array. As such, given your sample JSOns tring, you should be doing
(response.password[0] == 'This field is required')
Note the lack of []
brackets around the "this field..." text. Your code is effectively
if (string == array)
when it should be
if (string == string)
(using the same positions for the comparison members).
回答6:
you may try this:-
response['login'][0] == "This field is required."
回答7:
You can't compare arrays in JavaScript with ==
.
It's like this: {} == {} // false
two objects are not the same.
So you would also expect: new Foo() == new Foo(); // false
and similarly: new Array() == new Array() // false
[]
is shorthand for new Array()
(it's a little more complex, but ignore that for now).
来源:https://stackoverflow.com/questions/18831104/how-to-compare-a-value-in-javascript