I've been trying to get JSON from a Github user profile and post in dummy database then display the "image", "user name" and "real name" together with a div created by jQuery into a div in html.
But I'm stuck at appending my objects from JSON to the div. I know I got the format wrong but I don't know the right format, can someone help me with that? Thank you!
Here is the Javascript and HTML:
$(document).ready(function() {
var datas = $.get("https://api.github.com/users/iwenyou", function(infos) {
$.ajax({
type: "POST",
url: "https://httpbin.org/post",
data: infos,
dataType: "json",
success: function(data) {
$(".container").append("<div>datas['avatar_url']+datas.login+datas.name</div>");
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code.
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
Steps for Appending to a JSON File In Python, appending JSON to a file consists of the following steps: Read the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.
The key function that enables us to convert JSON to HTML at runtime is JSON. parse() . The JSON. parse() method takes textual JSON data and converts it to a JavaScript object.
Firstly the parameter you define in the $.ajax
callback is data
, not datas
and the properties you're trying to access are in the form
object of the response, so you need to use data.form
to access them.
Lastly, and most importantly, you need to concatenate the HTML string you create together with the values from the retrieved object. Try this:
$(document).ready(function() {
var datas = $.get("https://api.github.com/users/iwenyou", function(infos) {
$.ajax({
type: "POST",
url: "https://httpbin.org/post",
data: infos,
dataType: "json",
success: function(data) {
$(".container").append('<div>' + data.form.avatar_url + '</div><div>' + data.form.login + '</div><div>' + data.form.name + '</div>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"></div>
Note that the name
property is empty in the response, so it does not appear in the generated HTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With