Jquery Ajax Json Object
Basically I am trying to return a list of names gotten from an Ajax request. When there is only one name, it works perfectly. However with multiple names I start seeing behavior I can't explain.
function getIDFromInput(input){
sendToID = new Array; //An Array of "Name :Id"
$.ajax({
type:"GET",
u开发者_StackOverflow社区rl: "user_search.php",
contentType:"application/x-www-form-urlencoded; charset=utf-8",
dataType:"json",
async:false,
data: "q="+input,
success:function(data){
if(data.success){
var userLength = data.success.length;
if(userLength == 1){ // For one user everything works fine
var userNum = data.success.users[0];
var userName = data.success.usersNames[userNum];
sendToID[0] = userName + " :"+userNum;
}
else if(userLength > 1){ // Multiple users it fails
for(i = 0; i < userLength; i++){
var userNum = data.success.users[i];
//this call works
var userName = data.success.usersNames[userNum];
//this call fails, even though it seems to be the same call as above
sendToID[i] = userName + " :"+userNum;
}
}
else if(userLength < 1){ // never enter here
}
}
},
error:function(data){ //After it fails it goes into here
}
});
return sendToID;
}
The JSON I am passing back for < 2, ( The one that doesn't work, is below)
{"success":{"length":2,"userNames":[{"5":"Travis Baseler"},{"6":"Ravi Bhalla"}],"users":["5","6"]}}
The JSON I am passing back the one that does work is
{"success":{"length":"1","usersNames":{"6":"Ravi Bhalla"},"users":["6"]}}
Does anyone know why the first works but the second doesn't?
in your first example, "usernames"
is an array, and in the seconds one it's an object
(notice the []
in the first example which don't exist in the second one).
see @meagar's comment which explains this better than I did.
some further points:
1. you're using numbers as object property names; this (IMO) is not recommended since it's a bit confusing.
2. you can obtain the length of the array using the .length
property of an array:
var userNum = data.success.users.length
3. wouldn't it make more sense to have your objects in the format of { 'userNum': X, 'username': Y }
? that way you can return just one array:
success: [ {'userNum': 5, 'username': 'Travis Baseler'}, {'userNum': 6, 'username': 'Ravi Bhalla'}]
Your for loop should look like this:
for(i = 0; i < userLength; i++){
var userNum = data.success.users[i];
//this call works
var userName = data.success.userNames[i][userNum];//you need to index the user in the array in the object uisng the loop then user the userNum to get your userName.
sendToID[i] = userName + " :"+userNum;
}
精彩评论