简体   繁体   中英

How to set returned JSON Array to variable in jquery using AJAX

I'm trying to save my returned JSON Array to variable in jQuery. I was looking for solution and I found this one:

var ajaxjson = [];
    $.ajax({
        async: "false",
        dataType: "json",
        url: "http://localhost:8080/mywebapp/getJSONFromCity",
        data: {miasto: miasto},
        success: function(result) {
            ajaxjson = result;
        }
    });

also solutions from here: load json into variable , and here jQuery. Assign JSON as a result to a variable are not working for me:

var json = (function () {
   var json = null;
   $.ajax({
       'async': false,
       'global': false,
       'url': my_url,
       'dataType': "json",
       'success': function (data) {
           json = data;
       }
   });
   return json;
})();

AJAX call is working fine, I can show my 'result' data inside my success call, but I can't assign that data to variable any way. After that AJAX call my var is still null, when I'm trying to show some object from that, eg if I try to log "json[0].id" I get error " Uncaught TypeError: Cannot read property 'id' of undefined"

Any ideas how to fix it?

try 
'success': function (data) {
json = $.parseJSON(data);
return json;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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