我試圖通過JavaScript中的jQuery獲取json數據。但我無法從json獲取更新的數據,同時點擊更新按鈕。 Json數據網址也正常工作。如何在javascript中通過ajax獲取Json數據?
提到下面的代碼:我在上面的代碼
<!DOCTYPE html>
<html>
<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) {
// 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) {
var jsonObj = JSON.parse(http_request.responseText);
alert(jsonObj.name);
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("POST", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body> <h1>Cricketer Details</h1>
<div id="Name">Sachin</div>
<div id="Country">India</div>
<button type="button" onclick="loadJSON()">Update Details </button>
</body>
</html>
,我有JSON數據的URL。但點擊更新按鈕時,我可以通過ajax獲取json數據。
我找不到它在我的代碼中是錯誤的?
在此先感謝。
http://jsbeautifier.org – Pointy
上面的代碼你說*」,但我不能從中獲取更新的數據json,同時點擊更新按鈕。「*和下面的代碼你說*」,但點擊更新按鈕,我可以通過ajax獲得json數據。「*。現在是什麼?究竟是什麼問題? –
您無法從「http:// www.tutorialspoint.com/json/data.json」加載JSON文件。您需要複製它自己的Web服務器並將URL指向那裏。請參閱:http://en.wikipedia.org/wiki/Same-origin_policy –