【发布时间】:2023-03-13 07:42:01
【问题描述】:
如何在 jquery 中随机化每个循环项和 ajax / json 数据?
数据.json
{
"items" : [
{
"title" : "new1",
"content" : "content1"
},
{
"title" : "new2",
"content" : "content2"
},
{
"title" : "new3",
"content" : "content3"
},
{
"title" : "new4",
"content" : "content4"
}
]
}
jquery ajax 获取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
});
}
});
如何在 jquery 中随机化每个循环项和 ajax / json 数据?
【问题讨论】:
-
“如何随机化每个循环项” - 你的意思是“我如何随机排序/打乱
"items"数组?” -
这里你在代码中留下了一个大括号 }。所以可能这将是错误。以及为什么要返回该值。你知道回报会通过你的循环。
-
你能发布实际的 json 数据吗?这看起来像是硬编码的。
-
@nnnnnn 是的,我如何随机排序/随机排列限制为 2 个项目的“项目”数组,谢谢帮助!更新json格式