我有这个功能:
function: function getSimilar() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
var similar;
var id = parseInt(document.getElementById('similar').getAttribute('data-id')) || 0;
if(similar) {
document.querySelector('#similar').innerHTML = similar.Title;
document.getElementById('similar').setAttribute('data-id', similar.id);
}
},
error: function (data) {
console.error('Error in AJAX call');
console.error(data);
}
});
}
带有文章标题的Json文件:
[{
"id": 0,
"Title": "First Blog",
"Content": "Lorem Ipsum is simply dummy has been the industry's standard dummy text ever ."
}, {
"id": 1,
"Title": "Second Blog",
"Content": "industry. Lorem Ipsum has been the industry's standard dummy text ever since the ."
}, {
"id": 2,
"Title": "Third Blog",
"Content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum ."
}]
我想在我的一个叫做类似的html div中显示标题 任何人都可以帮我吗? 我想我应该在html中创建一个列表。 感谢
答案 0 :(得分:1)
像这样使用
var data = [{
"id": 0,
"Title": "First Blog",
"Content": "Lorem Ipsum is simply dummy has been the industry's standard dummy text ever ."
}, {
"id": 1,
"Title": "Second Blog",
"Content": "industry. Lorem Ipsum has been the industry's standard dummy text ever since the ."
}, {
"id": 2,
"Title": "Third Blog",
"Content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum ."
}];
for (i = 0; i < data.length; i++) {
$("#similar").append($("<span/>", { html: data[i].Title }));
$("#similar").append($("<span/>", { html: data[i].Content }));
$("#similar").append("<br/>");
}
修改强>
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
for (i = 0; i < data.length; i++) {
$("#similar").append($("<span/>", { html: data[i].Title, "data-id": data[i].id }));
}
},
error: function (data) {
console.error('Error in AJAX call');
console.error(data);
}
});
答案 1 :(得分:0)
您需要使用循环来迭代所有收到的项目,以便形成将添加到DOM的项目列表。为了创建大量新的DOM元素,我更喜欢在一些字符串缓冲区中收集它们然后立即添加 - 它更快一点,但不是必需的。您的代码可能是这样的:
<强>的JavaScript 强>
function getSimilar() {
$.ajax({
type: "GET",
url: "../Content/test.txt",
dataType: "json",
success: function (data) {
var i, l, list;
if(data && data.length > 0) {
list = ['<ul>'];
for(i=0,l=data.length; i<l; i++) {
list.push('<li data-id="' + data[i].id + '">' + data[i].Title + '</li>');
}
list.push('</ul>');
$('#similar').html(list.join(''));
}
},
error: function (data) {
console.error('Error in AJAX call');
console.error(data);
}
});
}
答案 2 :(得分:0)
如果您在回复中有jSon,即在数据中,您可以获得以下所有标题
success: function (data) {
for (i = 0; i < data.length; i++) {
$("#similar").append($("<span/>", { html: data.d[i].Title, "data-id": data.d[i].id }));
}
这是你在找什么?