开发者

Returning data from jQuery ajax request

开发者 https://www.devze.com 2022-12-19 03:43 出处:网络
I\'m trying to get a function to perform an ajax query and then return the interpreted JSON as an object.However for whatever reason, once this request is performed, the data is only accessible from w

I'm trying to get a function to perform an ajax query and then return the interpreted JSON as an object. However for whatever reason, once this request is performed, the data is only accessible from within the function.

    function getCacheImage(direction) {

            jQuery.ajax({ 
                    url: json_request_strin开发者_JS百科g,
                    success: function(data) {
                    return data;
                    }
            });

    }

How can I get this function to return 'data' appropriately?

Thanks.


You need to either use a synchronous ajax request (not typical or recommended) and capture the data into a variable in the outer scope, or figure out how to manipulate the data in the callback function. The problem is that the ajax function returns before the ajax call is complete -- it's asynchronous.

Synchronous way:

 function getCacheImage(direction) {
        var capture;
        jQuery.ajax({ 
                url: json_request_string,
                aSync: false,
                success: function(data) {
                   capture = data;
                }
        });
        return capture;
 }

Typical, using callback

 function getCacheImage(direction,callback) {

        jQuery.ajax({ 
                url: json_request_string,
                success: function(data) {
                   callback( data );
                }
        });
 }

 getCacheImage('left', function(data) {
      ...do something with the data...
 }


You can't. The first letter of the AJAX acronym stands for asynchronous, meaning that AJAX requests are sent and control is returned immediately to the calling function. What you need to do is to work with the data in the callback function.


You are returning the data to the code that calls the callback function. That code can not sent the data back in time so that it can be returned from the function that started the request.

Whatever you want to do with the data, you do in the callback function.

0

精彩评论

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

关注公众号