簡體   English   中英

jQuery Ajax Json對象

[英]Jquery Ajax Json Object

基本上,我試圖返回從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;
}

我傳回的<2的JSON,(不起作用的是,下面)

{"success":{"length":2,"userNames":[{"5":"Travis Baseler"},{"6":"Ravi Bhalla"}],"users":["5","6"]}}

我傳回的JSON確實有效

{"success":{"length":"1","usersNames":{"6":"Ravi Bhalla"},"users":["6"]}}

有誰知道為什么第一個可行,而第二個卻不可行?

在第一個示例中, "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'}]

您的for循環應如下所示:

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;
 }  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM