May 08, 2021 JSON
AJAX is asynchronous JavaScript and XML, a set of interrelated web development techniques for clients to create asynchronous web applications. Following the AJAX model, Web applications can send data asynchronously and retrieve data from the server without affecting the display behavior of existing pages.
Many developers use JSON to pass AJAX updates between clients and servers. A site that updates sports scores in real time can be considered an AJAX example. I f these grades are to be updated to the site, they must be stored on the server so that web pages can get them back when they are needed. Here we can use the data in JSON format.
Any data updated with AJAX can be stored on a Web server in JSON format. With AJAX, JavaScript can get these JSON files back if necessary, parse them, and then do two things:
The following code shows JSON and AJAX, save them as a .htm files. The load function loadJSON() here will upload JSON data asynchronously.
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<script type="application/javascript">
function loadJSON()
{
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e){
// IE 浏览器处理
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// 错误处理
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// 使用 JSON.parse 解析 JSON 数据
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj 变量现在包含数组结构,可以通过 jsonObj.name 和 jsonObj.country 的方式访问
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class="src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id="Name">Sachin</div></td>
<td><div id="Country">India</div></td></tr>
</table>
<div class="central">
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
Below is data.json, the input file that contains JSON format data, which is uploaded asynchronously when we click the Update Detail button. This file has been saved to http://www.tutorialspoint.com/json/ file.
{"name": "brett", "country": "Australia"}
The HTML code above produces a screen display like this, where you can do AJAX:
When we click the Update Detail button, we should get the results shown below, or you can try JSON and AJAX yourself to provide JavaScript supported by your own browser.