Jquery Ajax Json对象

Sha*_*hin 0 javascript ajax jquery json

基本上我正在尝试返回从Ajax请求中获取的名称列表.当只有一个名字时,它完美无缺.但是有多个名字,我开始看到我无法解释的行为.

function getIDFromInput(input){
    sendToID = new Array; //An Array of "Name :Id" 
    $.ajax({
        type:"GET",
        url: "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;
}
Run Code Online (Sandbox Code Playgroud)

我传回的JSON为<2,(那个不起作用的,在下面)

{"success":{"length":2,"userNames":[{"5":"Travis Baseler"},{"6":"Ravi Bhalla"}],"users":["5","6"]}}
Run Code Online (Sandbox Code Playgroud)

JSON我传回那个有效的JSON

{"success":{"length":"1","usersNames":{"6":"Ravi Bhalla"},"users":["6"]}}
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么第一个有效,但第二个没有?

J. *_* Ed 7

在你的第一个例子中,"usernames"是一个数组,在秒中它是一个对象
(注意[]第一个例子中第二个不存在的对象).
请参阅@ meagar的评论,这比我更好地解释了这一点.

还有一些要点:
1.你使用数字作为对象属性名称; 不建议使用此(IMO),因为它有点令人困惑.
2.你可以使用数组的.length属性获得数组的长度:
var userNum = data.success.users.length
3.将对象的格式设置为更合理{ 'userNum': X, 'username': Y }吗?这样你只能返回一个数组:
success: [ {'userNum': 5, 'username': 'Travis Baseler'}, {'userNum': 6, 'username': 'Ravi Bhalla'}]

  • 使用当前的数据类型,我认为@scrappedcola有正确的答案.但你的主要问题是:a.你为不同的情况返回了不同的数据结构,这非常糟糕(参见上面的@ meagar评论)和b.你以一种不那么有效的方式返回数据.如果你尝试我的建议,你可以做成功[i] .userNum`或`success [i] .username`这样更清洁 (3认同)