如何访问此ajax请求的返回值? [英] how do I access the return value of this ajax request?

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

问题描述

我有这个代码

var stats =  {
    GetMetaData : function() {
        var url = 'http://www.bungie.net/api/reach/reachapijson.svc/game/metadata/'+storage.get('apikey');
        $.ajax({
            url: url,
            success: function(data) {
                return data;
            }
        });
        return 'abc';
    }
}

我使用stats.GetMetaData();

我希望返回的值是ajax请求中的data变量. 但是,为什么是字符串"abc"呢?

I would expect the value returned to be the data variable from the ajax request. But instead it is the string 'abc' why is this?

如何返回data变量?

我尝试做return $.ajax({,但这只是返回功能代码.

I tried doing return $.ajax({ but that just return the function code.

推荐答案

因为默认情况下jquery ajax请求是异步的.您可以使用async: false选项或(最好)使用回调函数来使请求同步.
另外,如 CharlesLeaf 所述,使用同步请求将锁定浏览器,直到收到响应为止.

Because jquery ajax requests are asynchronous by default. You can make request synchronous by using async: false option or (better) use callback function.
Also, as CharlesLeaf notes, using synchronous request will lock up the browser until response is received.

关于异步操作的整个概念.
我会从jquery站点链接一些解释,但现在似乎已经结束.

About the whole concept of asynchronous operations.
I would link some explanation from jquery site, but it seems to be down now.

这篇关于如何访问此ajax请求的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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