[英]Storing JSON result from ajax request to a javascript variable for Easyautocomplete
[英]Global Javascript variable from AJAX JSON request
嗨我正在使用此代碼為我的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>
解決這個問題的最佳方法是使用所謂的回調函數。 回調函數是在特定事件發生時調用的函數。 在您的情況下,該事件是從JSON端點(URL)檢索的數據。
正確的方法是創建一個在接收數據時調用的函數,然后執行剩余的邏輯。 如果要使數據也可以全局訪問,則回調函數的一部分可以更新全局變量。
在下面的更新代碼中,我們首先聲明一個保存data
的全局變量globalJSON
。 在您收到任何數據之前(即在您單擊按鈕之前), globalJSON.data
的值將為null
。 收到數據后,將使用接收的數據調用回調函數updateView()
。 在updateView()
內部,我們更新全局變量globalJSON.data
並執行剩余的邏輯(即更新所需的HTML元素)。
然后,您可以在代碼中的任何其他位置使用globalJSON.data
來獲取單擊“ Update Details
按鈕時收到的數據。
// declare your global variable that will get updated once we receive data var globalJSON = { data: null } // this gets executed the moment you load the page - notice the value is null console.log(globalJSON.data); // this gets executed AFTER you receive data - notice call to updateView() inside AJAX call function function updateView(data) { // this will update the value of our global variable globalJSON.data = data; // this is the rest of the logic that you want executed with the received data document.getElementById("Name").innerHTML = data.name; document.getElementById("Country").innerHTML = data.country; // this will show that the global variable was in fact updated console.log(globalJSON.data); } 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); updateView(jsonObj); // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and 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>
如果您只想從事件處理程序外部訪問jsonObj,請將其顯式放在全局范圍內(無論這是否是個好主意)您可以通過window.jsonObj = JSON.parse(http_request.responseText);
在window
上創建jsonObj
。 window.jsonObj = JSON.parse(http_request.responseText);
但是你無法知道它何時在事件處理程序之外定義。 但是,它將滿足您對console.log(window.jsonObj)
(可能來自開發人員控制台)的要求。 如果你想看到值,你也可以在eventhandler中使用console.log(jsonObj)
。
完整代碼:
<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 ){
// Javascript function JSON.parse to parse JSON data
// if you want to be able to access this property from the developer console
window.jsonObj = JSON.parse(http_request.responseText);
// if you just want to see the value
console.log(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();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<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>
</body>
首先聲明一個變量,如var jsonObj= '';
(在你的函數里面。這個變量不是來自頁面上下文的全局變量,而是來自函數上下文) 。 訪問函數中的變量。 您使用http://www.tutorialspoint.com/json/data.json
但使用https
協議的原始網站的網址中存在的問題。 結果你得到了類似的錯誤
阻止加載混合活動內容“ http://www.tutorialspoint.com/json/data.json ”
因此,將URL更改為https://www.tutorialspoint.com/json/data.json
。 然后,您可以根據需要解析結果。
<title>tutorialspoint.com JSON</title> <body> <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> <script> function loadJSON(){ var jsonObj= ''; 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 jsonObj = JSON.parse(http_request.responseText); // jsonObj variable now contains the data structure and can // be accessed as jsonObj.name and jsonObj.country. console.log(jsonObj); document.getElementById("Name").innerHTML = jsonObj.name; document.getElementById("Country").innerHTML = jsonObj.country; } } http_request.open("GET", data_file, true); http_request.send(); } </script> </body>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.