jQuery JSON结果中的ForEach Array值

ForEach Array value in jQuery JSON result

本文关键字:ForEach Array JSON 结果 jQuery      更新时间:2023-09-26

好的,我想处理另一个javascript请求,foreach值在jQuery请求的JSON响应中返回,这是我用于该请求的当前代码

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处理数组,知道怎么做吗?

由于您已经在使用jQuery,您可以使用$.each函数:

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

使用一个简单的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);

以及在未实现的旧浏览器的情况下的讨论:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach所以你可以做