[英]Add returned data from ajax call to a UL then update jQuery quicksand
我正在建立用戶列表,並嘗試使用jQuery 流沙根據ajax請求返回的數據更新UL。
數據請求如下:
$.webMethod({
url: 'http://staging.cmdapp.com/Services/Poll.asmx/LeaderboardGetTopScores',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
beforeSend: function () { },
success: function (ret) {
$.each(ret.leaderboard,function(i){
// do something
});
},
error: function (response) { console.log(response.responseText); }
});
返回的數據是JSON字符串,每個用戶均由“ user_id”定義。 JSON數據(對不起,未格式化):
{"d":"{\"leaderboard\":[{\"user_id\":\"8\",\"first_name\":\"Kevin\",\"last_name\":\"McFarlane\",\"points\":\"1\",\"time_taken\":1408,\"incorrect_attempts\":0},{\"user_id\":\"9\",\"first_name\":\"Hanna\",\"last_name\":\"Gilbert\",\"points\":\"1\",\"time_taken\":4762,\"incorrect_attempts\":0},{\"user_id\":\"1\",\"first_name\":\"Adrian\",\"last_name\":\"Bathurst\",\"points\":\"0\",\"time_taken\":1616,\"incorrect_attempts\":0}]}"}
在我的html頁面中,我准備了流沙列表,如下所示:
<ul class="quicksand">
<li data-id="1">1</li>
<li data-id="2">2</li>
<li data-id="3">3</li>
<li data-id="4">4</li>
</ul>
我現在想在每個ajax請求上更新UL。 如何存儲返回的數據,並將每個單獨的“用戶”添加到單獨的LI項目中?
我嘗試了以下方法,但沒有運氣:
$.webMethod({
url: 'http://staging.cmdapp.com/Services/Poll.asmx/LeaderboardGetTopScores',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
beforeSend: function () { },
success: function (ret) {
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<li data-id="'+pos+'">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</li>';
});
$('.quicksand').quicksand( str, { adjustHeight: 'dynamic' } );
console.log(str);
},
error: function (response) { console.log(response.responseText); }
});
也許值得一提的是,我可以看到在每個ajax請求中將每個LI項中的正確數據拉入DOM中,但是它立即消失了,只顯示了第一個LI項。
您的JSON不正確。 密鑰d
值實際上是一個字符串,而不是一個對象,這就是您感到JSON Formatter無法正常工作的原因。 它實際上是有效的,但在對象上將其像字符串一樣對待。
您必須拆開引號將其視為對象,或使用$.parseJSON
將其轉換為對象。
$.webMethod({
url: 'http://staging.cmdapp.com/Services/Poll.asmx/LeaderboardGetTopScores',
data: '{quizIDs:"'+quizIDs+'",numRecords:"'+numRecords+'"}',
beforeSend: function () { },
success: function (ret) {
ret = $.parseJSON(ret.d);
$.each(ret.leaderboard,function(i){
pos = i + 1;
str = '<li data-id="'+pos+'">' + ret.leaderboard[i].first_name + ' ' + ret.leaderboard[i].last_name + '</li>';
});
$('.quicksand').quicksand( str, { adjustHeight: 'dynamic' } );
console.log(str);
},
error: function (response) { console.log(response.responseText); }
});
小提琴-http: //jsfiddle.net/rttAZ/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.