- JSON 有用資源
- JSON - 快速指南
- JSON - 有用資源
- JSON - 討論
使用 Ajax 的 JSON
AJAX 是非同步 JavaScript 和 XML,它在客戶端用作一組相互關聯的 Web 開發技術,以建立非同步 Web 應用程式。根據 AJAX 模型,Web 應用程式可以非同步地向伺服器傳送和檢索資料,而不會干擾現有頁面的顯示和行為。
許多開發人員使用 JSON 在客戶端和伺服器之間傳遞 AJAX 更新。更新即時體育比分的網站可以被認為是 AJAX 的一個示例。如果這些分數必須在網站上更新,則必須將它們儲存在伺服器上,以便網頁在需要時可以檢索分數。這就是我們可以使用 JSON 格式化資料的地方。
任何使用 AJAX 更新的資料都可以使用 JSON 格式儲存在 Web 伺服器上。使用 AJAX,以便 Javascript 可以根據需要檢索這些 JSON 檔案,解析它們,並執行以下操作之一:
在網頁上顯示之前,將解析的值儲存在變數中以進行進一步處理。
它直接將資料分配給網頁中的 DOM 元素,以便它們顯示在網站上。
示例
以下程式碼顯示了使用 AJAX 的 JSON。將其儲存為ajax.htm檔案。這裡,載入函式 loadJSON() 用於非同步上傳 JSON 資料。
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON() {
var data_file = "https://tutorialspoint.tw/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4 ) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and 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>
</div>
</body>
</html>
下面給出的是輸入檔案data.json,其中包含 JSON 格式的資料,當我們點選更新詳細資訊按鈕時,將非同步上傳這些資料。此檔案儲存在https://tutorialspoint.tw/json/
{"name": "Brett", "country": "Australia"}
上面的 HTML 程式碼將生成以下螢幕,您可以在其中檢查 AJAX 的實際操作:
板球運動員詳細資訊
| 姓名 | 國家 |
|---|---|
薩欽 |
印度 |
當您點選更新詳細資訊按鈕時,您應該會得到如下結果。您可以嘗試 使用 AJAX 的 JSON,前提是您的瀏覽器支援 Javascript。
板球運動員詳細資訊
| 姓名 | 國家 |
|---|---|
佈雷特 |
澳大利亞 |
廣告