最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery store json object from url in javascript variable - Stack Overflow

programmeradmin1浏览0评论

How do I use the .getJSON() function to save a json object as a javascript variable?

var js = 
$.getJSON(url, 
    function(data) {...}
);

do I need the function(data) {...} callback?

The var would look like normal json format (like a dictionary in python?)

{"query":{"count":1,"created":"2014-07-18", ...

How do I use the .getJSON() function to save a json object as a javascript variable?

var js = 
$.getJSON(url, 
    function(data) {...}
);

do I need the function(data) {...} callback?

The var would look like normal json format (like a dictionary in python?)

{"query":{"count":1,"created":"2014-07-18", ...
Share Improve this question edited Jul 18, 2014 at 5:33 brno792 asked Jul 18, 2014 at 5:08 brno792brno792 6,80918 gold badges57 silver badges72 bronze badges 2
  • The function(data){...} part is the callback of getJSON, data is the JSON response that you will get. – Teh SoTo Commented Jul 18, 2014 at 5:10
  • You mean you want to receive data returned by $.getJSON in a JavaScript variable? – AdityaParab Commented Jul 18, 2014 at 5:10
Add a ment  | 

2 Answers 2

Reset to default 7

You would need to declare the variable first and then assign the value in the success function as such:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);

EDIT:

If your code looks something like the following, then it probably won't work:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);
$("div").html(js);

That's because the $.getJSON() is an asynchronous function. That means the code underneath will continue executing without waiting for the $.getJSON to finish. Instead you would want to use the variable inside the success function as such:

var js;
$.getJSON(url, 
    function(data) {
        // the code inside this function will be run,
        // when the $.getJSON finishes retrieving the data
        js = data;
        $("div").html(js);
    }
);

Assuming you want to receive data returned by $.getJSON in a javascript variable.

var js;

$.getJSON(url, function(data) {
    js = data;
    // you can even pass data as parameter to your target function like myFunct(data);
});
发布评论

评论列表(0)

  1. 暂无评论