【发布时间】:2018-02-22 22:52:37
【问题描述】:
您好,我正在将此代码用于我的 AJAX JSON 请求,但对于某些人来说,如果我尝试将 jsonObj 设为全局变量,而 console.log() 在调试器控制台中始终显示为未定义
为了澄清我的问题,如何从 AJAX JSON 请求中检索全局变量
function loadJSON() {
var data_file = "https://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) {
// 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();
}
<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>
【问题讨论】:
-
使用您提供的代码似乎可以按预期工作 - see demo here。您能否更具体地说明为什么需要将 json 数据作为全局变量?
-
我将您的代码更改为使用 https 并且它可以正常工作
-
请查看我的answer,了解实现所需功能的正确方法。
标签: javascript html json ajax