Set javascript global variable to JSONresult?

牧云@^-^@ 提交于 2019-12-24 09:24:40

问题


how do i set a js global variable to a json result set in the onload event?

    var global = [];

    $.getJSON("<%: Url.Action("myUrl", "con") %>/", 
     function(data) {
           $.each(data, function(key, val) {
             global.push(val);
           });
    });

global does not have a value set on load, i need to access it outside the json call...


回答1:


You again. Maybe try

var result;
$.ajax({
    url: '<%: Url.Action("myUrl", "con") %>/',
    dataType: 'json',
    async: false,
    success: function(data) {
        result = data;
    }
});
// process result here



回答2:


You don't need to set global to an array. Just assign the value.

var global = null;

    $.getJSON("<%: Url.Action("myUrl", "con") %>/", 
     function(data) {
           $.each(data, function(key, val) {
             global = val;
           });
    });



回答3:


That code should work just fine. (Live copy) Sounds like there's a problem with the ajax call not returning the data in the form you expect.




回答4:


As @marc (indirectly) points, you have to understand the nature of the ajax call, and event model. The ajax call is executed as soon as the JS file is parsed, byt result is returned asynchronously. So, your code timeline would look like

00 set global = []
01 AJAX call /someurl/ -------------------\
02 check global /* it's empty */           \
03 do something else                  [process AJAX call on server, send result]
...                                         /
42 AJAX call is completed <----------------/
43 call  success ----------------------------------> global.push(result)
44 at this point of time you can access global

This is a timeline, not the execution order. The time between the AJAX call and the response could be arbitrary, including the case of timeout or server-side error

So, what should you do?

1) the normal solurtion for JS - a callback, the success function you already have could either

1.1) set global and call the other function, or

1.2) do the desired actions with data

2) event - better if you suppose to use the data in multiple parts of the code, read for jQuery events mechanism

3) synchronous call, as @marc suggests - this should be avoided in 99% of cases. The only case I know when itt might be needed is when you have to requst for mandatory data from the 3rd party source, and even in this case you could do it on server (though at least synchronous AJAX is acceptable)



来源:https://stackoverflow.com/questions/6830283/set-javascript-global-variable-to-jsonresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!