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 . 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]);
}
});
}
});
Any Ideea ?
There is wrong in calling API in ajax method.
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.
You can make it more simple by using 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/ )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.