繁体   English   中英

来自AJAX JSON请求的全局Javascript变量

[英]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上创建jsonObjwindow.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM