Using asynchronous Javascript or AJAX to load information from JSON is very common in web development. Here is an example of using jQuery to show data on the website by loading external JSON file.
Step 1)
Create a folder called learnjQuery
on your website.
Step 2) Create the html file
Use sublime text or whatever text editor you like to create an html file.
Enter the following code to set-up your html file.
1 2 3 4 5 6 7 8 9 10 11 | <html lang='en'> <head> <meta charset ="utf-8"> <title>Test</title> </head> <body> <div id="update"></div> <script src="jquery.js" type="text/javascript"></script> <script src="script.js" type="text/javascript"></script> </body> </html> |
Save this file as “index.html
” in your learnjQuery folder.
Step 3 Create the Javascript file
Open your sublime and then copy the following code
1 2 3 4 5 6 7 8 9 | $.getJSON('data.json',function(data){ console.log(data); var output = '<ul>'; $.each(data, function(key,val){ output += '<li>'+ val.name + " " + val.zipcode+ '</li>'; }); output += '</ul>'; $('#update').html(output); }); |
Save the file as “script.js” in the learnjQuery folder.
Step 4) Get jQuery from their website
Visit http://jquery.com/
Click the Download jQuery (the brownish button) on the right side.
Then, you will see this page.
Click the “Download the uncompressed, development jQuery 2.1.4.”
Simply, download the latest version if you see a different version than me.
Save the file as “jquery.js
” in the learnjQuery folder.
Step 4) Build a sample data.json
Open Sublime or any text editor and copy the following data into an empty file.
1 2 3 4 5 6 7 8 9 10 11 12 13 | [ {"name":"Shenzhen", "zipcode":"518000" }, { "name":"Beijing", "zipcode":"100000" }, { "name":"Shanghai", "zipcode":"200000" } ] |
Save the file as “data.json
” in your learnjQuery folder.
Step 5) The Grand Finale
Now, you should have the following files in your learnjQuery folder.
You can use Safari to open the index.html
.
If you use Chrome, you may see failure because Chrome has a cross origin issue. It tends to be better to use Safari for testing.
You will see the contents of your JSON file.
Congratulations! You just finished using technology that most social networks are using.