简体   繁体   English

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

[英]Global Javascript variable from AJAX JSON request

Hi i am using this code for my AJAX JSON request but for some if i try to make jsonObj a global variable and console.log() it always comes up as undefined in the debugger console 嗨我正在使用此代码为我的AJAX JSON请求,但对于一些如果我尝试使jsonObj成为一个全局变量和console.log()它总是在调试器控制台中出现未定义

To clarify my question, how can I retrieve a global variable from an AJAX JSON request 为了澄清我的问题,我如何从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> 

The best way to approach this is by using what's called a callback function. 解决这个问题的最佳方法是使用所谓的回调函数。 A callback function is a function that is invoked when specific event takes place. 回调函数是在特定事件发生时调用的函数。 In your case that event is the data being retrieved from your JSON endpoint (URL). 在您的情况下,该事件是从JSON端点(URL)检索的数据。

The proper way to do this is to create a function that will be called when your data is received and will then carry out the remaining logic. 正确的方法是创建一个在接收数据时调用的函数,然后执行剩余的逻辑。 If you want to make that data also accessible globally, part of the callback function can update your global variable. 如果要使数据也可以全局访问,则回调函数的一部分可以更新全局变量。

In the updated code below we first declare a global variable globalJSON that holds our data . 在下面的更新代码中,我们首先声明一个保存data的全局变量globalJSON Before you receive any data (ie before you click the button) the value of globalJSON.data will be null . 在您收到任何数据之前(即在您单击按钮之前), globalJSON.data的值将为null Once the data is received the callback function updateView() is called with the received data. 收到数据后,将使用接收的数据调用回调函数updateView() Inside of updateView() we update the global variable globalJSON.data and carry out the remaining logic (ie updating the required HTML elements). updateView()内部,我们更新全局变量globalJSON.data并执行剩余的逻辑(即更新所需的HTML元素)。

You can then use globalJSON.data anywhere else in your code to get the data received when Update Details button was clicked. 然后,您可以在代码中的任何其他位置使用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> 

If you just want to access jsonObj from outside of the event handler, explicitly place it on the global scope (regardless of whether this is a good idea) you could create jsonObj on window by window.jsonObj = JSON.parse(http_request.responseText); 如果您只想从事件处理程序外部访问jsonObj,请将其显式放在全局范围内(无论这是否是个好主意)您可以通过window.jsonObj = JSON.parse(http_request.responseText);window上创建jsonObjwindow.jsonObj = JSON.parse(http_request.responseText);

But you won't have any way of knowing when it's defined outside of the event handler. 但是你无法知道它何时在事件处理程序之外定义。 However, it would fulfill your requirement of being able to console.log(window.jsonObj) (presumably from the developer console). 但是,它将满足您对console.log(window.jsonObj) (可能来自开发人员控制台)的要求。 Also you could just console.log(jsonObj) in the eventhandler if you wanted to see the value. 如果你想看到值,你也可以在eventhandler中使用console.log(jsonObj)

full code: 完整代码:

<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>

Declare a variable at first like var jsonObj= ''; 首先声明一个变量,如var jsonObj= ''; ( Inside your function. This variable is not global from the page context, but from the function context ) . (在你的函数里面。这个变量不是来自页面上下文的全局变量,而是来自函数上下文) access the variable in your function. 访问函数中的变量。 A problem in your url that you use http://www.tutorialspoint.com/json/data.json but the original site using https protocol. 您使用http://www.tutorialspoint.com/json/data.json但使用https协议的原始网站的网址中存在的问题。 As a result you got an error something like that 结果你得到了类似的错误

Blocked loading mixed active content " http://www.tutorialspoint.com/json/data.json " 阻止加载混合活动内容“ http://www.tutorialspoint.com/json/data.json

So change the url also to https://www.tutorialspoint.com/json/data.json . 因此,将URL更改为https://www.tutorialspoint.com/json/data.json Then you can parse the result as you want. 然后,您可以根据需要解析结果。

 <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