2013-02-10 62 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