[英]Display posts from json
I have to display posts from json , but when i try to use for loop nothing happen .. Here is My code , what i've do wrong . 我必须显示json的帖子,但是当我尝试用于循环时,什么也没发生。这是我的代码,我做错了。 ty TY
JS JS
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root,
method: 'GET',
success: function(response) {
console.log(response);
jQuery.get('/posts', function(posts) {
for (var i = 0; i < posts.length; i++) {
document.write(posts[i]);
}
});
}
});
Any Ideea ? 有想法吗?
There is wrong in calling API in ajax method. 在ajax方法中调用API是错误的。
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root+"/posts",
method: 'GET',
contentType: 'application/json',
success : function(data) {
//The 'data' u recieve here is the response from the api, Use this data to loop through and display it in the web page
},
error: function(err) {
console.log("err");
}
}
});
Try the above snippet, I hope it works 试试上面的代码片段,希望它能起作用
var root = 'https://jsonplaceholder.typicode.com'; $.ajax({ url: root+"/posts", method: 'GET', contentType: 'application/json', success: function(posts) { console.log("Data=>",posts); $.each(posts,function(index,post){ document.write("<p>"+post.title+"</p>"); }); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
You should give proper URL root+'/posts'
in order to fetch data from API. 您应该提供正确的URL root+'/posts'
,以便从API提取数据。
You can make it more simple by using jQuery.get
您可以使用jQuery.get
使其更简单
$.get('https://jsonplaceholder.typicode.com/posts',function(data){
$.each(data,function(key,post){
$('body').append('<p>'+post.title+'</p>');
});
});
check the documentation ( https://api.jquery.com/jquery.get/ ) 检查文档( https://api.jquery.com/jquery.get/ )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.