0
我一直在爲此工作了一個小時,但似乎無法弄清楚。JQuery訪問一些JSON數據
JSON響應:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
這似乎是正確的,現在的jQuery:一個爲this.lastId
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
的console.log("this.lastDate = " + this.lastDate);
作品,也是如此。 this.response
也可以正常工作,並很好地顯示了一個從索引0
開始的數組,並且在展開它時可以看到開發者視圖中的所有元素。
現在來我似乎無法理解的部分:在foreach
超過this.response
未打印的this
有用的東西(除了原型骨架)。
如何訪問值?
當你說*「foreach」*,你是否引用這條線? 'this.response.each(new function(){'它可能應該是'forEach'。一旦改爲'forEach',你需要使用回調參數而不是'this'來訪問數組值。 –
'this.response.each'甚至不應該工作,因爲數組沒有'each'方法。另外,'new function(){...}'肯定是錯誤的,這會傳遞一個* instance *(我也建議你保持一致:使用jQuery方法或使用本地JS方法 –
爲什麼在這裏使用迭代器'$(json).each(function (){'?根元素不是一個數組,你真的想遍歷返回的對象的屬性嗎?它看起來不像你試圖使用'this.lastId' –