1

さて、jQueryリクエストからのJSONレスポンス内に返された別のjavascriptリクエスト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を使用して配列を処理する方法がわかりません。

4

2 に答える 2

2

すでに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);
})
于 2013-02-10T14:49:42.943 に答える
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);

暗黙的ではない古いブラウザの場合の議論:https ://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach

于 2013-02-10T15:09:20.603 に答える