jQuery的getJSON()方法用於通過 HTTP GET 請求從服務器獲取JSON編碼的數據。下面本篇文章就來給大家介紹一下getJSON()方法,希望對大家有所幫助。
原文地址:jQuery的getJSON()方法有什麼用?
語法:
$(selector).getJSON(url,data,success(data,status,xhr))
參數:此方法接受上述三個參數
● url:這是必需的參數;它用於以請求發送到的字符串的形式指定URL。
● data:它是一個可選參數,用於指定將發送到服務器的數據。
● callback:它也是一個可選參數,在請求成功時運行。
返回值:返回XMLHttpRequest對象。
下面的例子演示了jQuery中的getJSON()方法:
text.json文件:
{
"name": "Tom",
"age" : "20",
"role": "Engineer"
}
示例:獲取JSON文件並顯示其內容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> jQuery getJSON()方法</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("button").click(function(event) {
$.getJSON('test.json', function(emp) {
$('#demo').html('<p> Name: ' + emp.name + '</p>');
$('#demo').append('<p>Age : ' + emp.age + '</p>');
$('#demo').append('<p> Role: ' + emp.role + '</p>');
});
});
});
</script>
</head>
<body>
<p>點擊按鈕,獲取數據</p>
<button>獲取 JSON 數據</button>
<p id="demo"></p>
</body>
</html>
效果圖:
推薦閱讀: