【问题标题】:ForEach Array value in jQuery JSON resultjQuery JSON 结果中的 ForEach 数组值
【发布时间】:2013-01-25 18:32:17
【问题描述】:

好的,我想处理另一个 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 来处理数组,知道怎么做吗?

【问题讨论】:

标签: javascript jquery ajax arrays foreach


【解决方案1】:

由于您已经在使用 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);
})

【讨论】:

    【解决方案2】:

    使用简单的 for 循环,可能比 for each 更快

    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 这样你就可以做到这一点

    【讨论】:

    • 我假设 msg_id 在根级别的每个元素中。
    猜你喜欢
    • 2023-03-11
    • 2021-01-23
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多