[英]Display posts from json
我必須顯示json的帖子,但是當我嘗試用於循環時,什么也沒發生。這是我的代碼,我做錯了。 TY
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]);
}
});
}
});
有想法嗎?
在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");
}
}
});
試試上面的代碼片段,希望它能起作用
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>
您應該提供正確的URL root+'/posts'
,以便從API提取數據。
您可以使用jQuery.get
使其更簡單
$.get('https://jsonplaceholder.typicode.com/posts',function(data){
$.each(data,function(key,post){
$('body').append('<p>'+post.title+'</p>');
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.