我如何使用http://example.com/file.json之类的远程网址而不是本地文件
$.get("file.json", function(data) {
$.each(data.posts, function(){
$("body").append("Name: " + this.title);
});
}, "json");
答案 0 :(得分:1)
$.get("file.json", function(data) {
$.each(data.posts, function(){
$("body").append("Name: " + this.title);
});
}, "json");
答案 1 :(得分:0)
要遍历数据数组,您可以使用jQuery的每个方法。 作为优化,我建议首先将所有html写入变量,并且只有在循环结束后才通过appendTo访问DOM。试试这个:
var content = '';
jQuery.get('file.json', function(data){
var posts = data.posts;//assumse the posts property of the returned object is the data array you want to iterate over
jQuery.each(posts, function(index, item){
content += item.title + '<br/>;' //build html string here
});
//Only attempt to insert if there is something to insert
if (content) {
content.appendTo('body);
/**
* You could also use vanilla JS here for this step
* ie: document.body.innerHTML = content;
**/
}
});