2012-09-11 68 views
0

有人可以告訴我爲什麼這不起作用嗎?Jquery-每個循環都不更新變量

var items = "<select id=\"orderer_search\" name=\"search\">"; 
    $.getJSON("https://dev.xxx.com", 
    function(data){ 
    $.each(data, function(index,item) { 
     items += "<option value='" + item + "'>" + item + "</option>"; 
    });   
    }); 

    items += "</select>"; 

如果我把之前的警報(項):

items += "</select>"; 

值是:

<select id="orderer_search" name="search"> 

但是,如果我把在每個循環警報,每個彈出窗口顯示從JSON請求返回的值。

這幾乎就像只要每個循環結束,它是消除我的每一個循環過程中添加到items變量的一切。我是JQuery的新手,所以我相信這很簡單。

+1

作爲每對夫婦的答案:你可以使用一個'ajax'呼叫是有'異步:FALSE'如果你沒有其他選擇。 –

回答

2

這不是刪除一切,JSON的請求只是沒有當你做items += "</select>";完蛋了!

$.getJSON異步運行,這意味着該語句開始請求到指定的URL,但它並沒有等待回答,程序流程然後就繼續與下一個語句(你的情況items += ...,無需等待爲$.getJSON完成!只有當響應到達的時候,給成功函數被調用。

你必須在如何解決這個問題,有兩種選擇。 方案1將被推遲items字符串的所有組合,直到$.getJSON成功:

$.getJSON("https://dev.xxx.com", 
    function(data){ 
     var items = "<select id=\"orderer_search\" name=\"search\">"; 
     $.each(data, function(index,item) { 
      items += "<option value='" + item + "'>" + item + "</option>"; 
     }); 
     items += "</select>"; 
     alert(items); // or whatever else you have to do with items 
    } 
); 

備選2將make the $.getJSON call non-asynchronous,以便該函數等待響應來。你不得不使用$.ajax功能,像這樣:

var items = "<select id=\"orderer_search\" name=\"search\">"; 
$.ajax({ 
    url: "https://dev.webshop.restore.net.au/_pag/shop/TEST/? 
      bc=TEST&sec=order%2F&pag=get_orderers_list", 
    dataType: 'json', 
    async: false, 
    success: function(data) { 
     $.each(data, function(index,item) { 
      items += "<option value='" + item + "'>" + item + "</option>"; 
     } 
    } 
}); 
items += "</select>"; 
alert(items); // or whatever else you have to do with items 

方案1有潛力使你的腳本更加敏感,如果有什麼要填滿這個選擇做開;因爲那麼請求將在後臺運行,準平行於您的其他代碼。所以我通常會這麼做。

+0

謝謝。寫得很好的答案 – Lock

1

試過這樣.. ???

var items = "<select id=\"orderer_search\" name=\"search\">"; 
$.getJSON("https://dev.webshop.restore.net.au/_pag/shop/TEST/? 
      bc=TEST&sec=order%2F&pag=get_orderers_list", 
function(data){ 
$.each(data, function(index,item) { 
    items += "<option value='" + item + "'>" + item + "</option>"; 
}); 
    items += "</select>"; 
}); 
0

$ .getJSON()函數是異步的,這意味着您稍後會得到結果。

items += "</select>"; 

你所要做的是執行你的AJAX請求的答案evertything:

之前,所以在執行這部分代碼。

var items; 
    $.getJSON("https://dev.webshop.restore.net.au/_pag/shop/TEST/? 
       bc=TEST&sec=order%2F&pag=get_orderers_list", 
    function(data){ 
    items = "<select id=\"orderer_search\" name=\"search\">"; 
    $.each(data, function(index,item) { 
     items += "<option value='" + item + "'>" + item + "</option>"; 
    }); 
    items += "</select>"; 
    });