Reputation: 1248
Just start practicing ajax using this fake api service. JSONPlaceholder
But I'm confused with displaying data to html file. I just want to show data like this.
Blog title: unt aut facere repellat provident occaecati excepturi optio reprehenderit (comes with jason file)
Blog post: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto" (comes with jason file)
It has provided root
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(data);
});
How can I display data to html?
Upvotes: 0
Views: 4520
Reputation: 981
You can display the JSON data in your HTML using Data Object Manipulation (DOM) in JavaScript.
You can do it like this in jQuery:
<p>Hello World</p>
<script>
var root = "https://jsonplaceholder.typicode.com";
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$("p").html(data.title);
});
</script>
Upvotes: 1
Reputation: 760
Display json data into html with below from the json response,
$("div").html('<div>'+data.title+'</div><div>'+data.description+'</div>');
Upvotes: 1
Reputation: 2583
Supposing you have such json:
{
title: 'My awesome title',
description: 'My awesome description'
}
And such HTML code:
<h1 id="title"></h1>
<div id="description"></div>
You should do
$('#title').text(data.title);
$('#description').text(data.decription);
instead of
console.log(data);
Upvotes: 3