如何使用 jQuery 和 Ajax 從 JSON 檔案中檢索資料?
要使用 jQuery 和 Ajax 從 JSON 檔案中檢索資料,請使用 jQuery.getJSON( url, [data], [callback] )
jQuery.getJSON( url, [data], [callback] ) 方法使用 GET HTTP 請求從伺服器載入 JSON 資料。
以下是此方法使用的所有引數的描述 −
- url − 包含將傳送請求的 URL 的字串
- data − 此可選引數表示將傳送至伺服器的關鍵字/值對。
- callback − 此可選引數表示每當資料成功載入時一個將被執行的函式。
假設我們在 result.json 檔案中具有以下 JSON 內容 −
{
"name": "John",
"age" : "30",
"sex": "male"
}以下是展示此方法使用情況的程式碼片段 −
示例
<head>
<title>The jQuery Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#driver").click(function(event){
$.getJSON('result.json', function(jd) {
$('#stage').html('<p> Name: ' + jd.name + '</p>');
$('#stage').append('<p>Age : ' + jd.age+ '</p>');
$('#stage').append('<p> Sex: ' + jd.sex+ '</p>');
});
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file:</p>
<div id = "stage" style = "background-color:#cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP