从jQuery ajax请求返回数据 [英] Returning data from jQuery ajax request

查看:84
本文介绍了从jQuery ajax请求返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取一个函数来执行ajax查询,然后将解释的JSON作为对象返回。但无论出于何种原因,一旦执行此请求,数据只能在函数内访问。

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_string,
                    success: function(data) {
                    return data;
                    }
            });

    }

如何让这个函数适当地返回'data' ?

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

谢谢。

推荐答案

你需要使用同步ajax请求(不是典型的或推荐的)并将数据捕获到外部作用域中的变量中,或者弄清楚如何操作回调函数中的数据。问题是ajax函数在ajax调用完成之前返回 - 它是异步的。

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.

同步方式:

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

典型,使用回调

 function getCacheImage(direction,callback) {

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

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

这篇关于从jQuery ajax请求返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆