2013-02-10 48 views
1

好吧,我想處理從一個jQuery請求的JSON響應內返回另一個JavaScript要求的foreach值,下面是當前的代碼我使用這個請求的ForEach數組值

function waitForEvents(){ 
$.ajax({ 
      type: "GET", 
      url: "/functions/ajax.php?func=feed&old_msg_id="+old_msg_id, 

      async: true, /* If set to non-async, browser shows page as "Loading.."*/ 
      cache: false, 
      timeout:50000, /* Timeout in ms */ 

      success: function(data){ 
       var json = jQuery.parseJSON(data); 
       **//Foreach json repsonse['msg_id'] call another function** 
       setTimeout('waitForEvents()',"1000"); 
      }, 

      error: function (XMLHttpRequest, textStatus, errorThrown){ 
       alert("Error:" + textStatus + " (" + errorThrown + ")"); 
       setTimeout('waitForEvents()',"15000");  
      }, 
}); 
}; 

爲每個JSON響應變量['msg_id']我想調用另一個JavaScript函數,但不知道如何處理在JavaScript中使用foreach的數組,任何想法如何?

+0

的[我有一個嵌套的數據結構/ JSON,我怎麼能訪問可能重複具體的價值?](http://stackoverflow.com/questions/11922383/i-have-a-nested-data-structure-json-how-can-i-access-a-specific-value) – 2013-02-10 14:55:30

回答

2

正如你已經在使用jQuery,您可以使用$。每個功能:

http://api.jquery.com/jQuery.each/

$.each(json.msg_id, function (index, value) { 
    // Do something with value here, e.g. 
    alert('Value ' + index + ' is ' value); 
}) 
+0

謝謝你,作品完美! – 2013-02-10 14:53:56

+0

沒問題,我的榮幸。 – ChrisC 2013-02-10 14:56:29

0

使用一個簡單的for循環,可能不是每個

function myfunction(id){ 
    alert("myid:"+id): 
} 

var i=0; 
for (i=0; i< json.length;i++){ 
    var thisId = json[i].msg_id; 
    myfunction(thisId); 
} 

簡單:

function myfunction(id){ 
    alert("myid:"+id): 
} 

var i=0; 
for (i=0; i< json.length;i++){ 
    myfunction(json[i].msg_id); 
} 

既然你問:

function checkArrayElements(element, index, array) { 
    console.log("a[" + index + "] = " + element); 
    var myId = element.msg_id; 
}; 
json.forEach(checkArrayElements); 

,並在案例討論舊的瀏覽器,其中不implimented:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach這樣你就可以做到這一點

+0

我假設msg_id位於根級別的每個元素中。 – 2013-02-10 15:10:58