如何使用 jQuery 載入 JSON 資料?
要使用 jQuery 載入 JSON 資料,請使用 getJSON() 和 ajax() 方法。jQuery.getJSON( ) 方法使用 GET HTTP 請求從伺服器載入 JSON 資料。
下面是此方法使用到的所有引數的說明 −
- url − 包含傳送請求的 URL 的字串
- data − 該可選引數表示將傳送到伺服器的鍵/值對。
- callback − 該可選引數表示在成功載入資料時要執行的函式。
在 result.json 檔案中新增你的 JSON 內容 −
{
"name": "Amit",
"age" : "27",
"sex": "male"
}下面是一段程式碼片段,演示了該方法的使用。它連結了上面建立的 result.json 檔案,
示例
<head>
<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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP