如何随机每个循环项目,并在jQuery的AJAX / JSON数据? [英] How to random each loop item and on ajax / json data in jquery?
本文介绍了如何随机每个循环项目,并在jQuery的AJAX / JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何随机每个循环项目和AJAX / JSON数据的jQuery?
How to random each loop item and on ajax / json data in jquery ?
data.json
data.json
{
"items" : [
{
"title" : "new1",
"content" : "content1"
},
{
"title" : "new2",
"content" : "content2"
},
{
"title" : "new3",
"content" : "content3"
},
{
"title" : "new4",
"content" : "content4"
}
]
}
jQuery的AJAX获取JSON
jquery ajax get json
$.ajax({
url: 'data.json',
type: 'get',
dataType: 'json',
async: false,
success: function(data){
$.each(data.items, function(index,item) {
var template = '<p>' + item.title + '</p>' + item.content + '<br />';
$('html').append(template);
return index < 1 ; // set 2 item
});
}
});
如何随机每个循环项目和AJAX / JSON数据的jQuery?
How to random each loop item and on ajax / json data in jquery ?
推荐答案
添加键,也靠近
每个()
添加});
在年底每个()
Add '
and also close .each()
add });
at the end of .each()
$.each(data.items, function(index,item) {
var template = '<p>' + item.title + '</p>' + item.content + '<br />'; });
随机
var random_index = Math.floor(Math.random()*data.length);
var item = data[random_index];
这篇关于如何随机每个循环项目,并在jQuery的AJAX / JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文