开发者

jQuery: Fetch Ajax to variable?

I thought that the below shown code would work as a charm, but apparently it doesn't. I can't tell why it isnt working - The URL is fetched properly (checked 开发者_StackOverflow中文版with firebug) but it refuses to save the result to my variable (globalVar).

What can I do?

var globalVar;  

function fetchDataset(kategori){  

    $.getJSON(apiUrl + "?jsoncallback=?", function(json){
        globalVar = json;

        console.log(globalVar); // Returns Undefined!
    });


}


I guess firebug should display the contents of your callback. I had a similar problem and solved it using .parseJSON();

http://api.jquery.com/jQuery.parseJSON/

Maybe it helps.

Is the callback neatly formatted/"correct" json?


Your variable is not global. You defined it within the scope of the function. Your Ajax call is run asynchronously which means that your function will complete (probably) before the ajax request is returned. Try declaring globalVar outside of the function. ie.

var globalVar;    
function fetchDataset(kategori){

Edit: Also, check the statusText (second variable passed to the callback function) to make sure that there are no errors with your request.


Are you making a cross domain request?

If so make sure you use jsonp

JSONP If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

There is an example here of jsonp. http://api.jquery.com/jQuery.getJSON/


Apparently, nothing worked, so I instead ending up making a PHP-based proxy that tunnels any cross-domain request. After changing the url to the PHP proxy, it worked great.

Thanks for everyones help. Very appreciated!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜