得到$ .ajax响应 [英] get $.ajax response

查看:75
本文介绍了得到$ .ajax响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function Profiles() { };

Profiles.prototype.test = function() {
    var opt = {
        url: __profileurl__+'getall/', type: 'get', dataType:'json',
        success:function(response){
          return response;
        }
    };      
    $.ajax(opt);
};

var profile = new Profiles(); 

var r = profile.test(); 

//返回undefined ...预期的输出应该是请求的响应.

// returns undefined... expected output should be the response from the request.

推荐答案

可以通过异步请求执行此操作,但这通常是错误的事情

You can do it with an async request, but it's generally a Bad Thing

像下面这样的东西应该返回数据.

Something like the following oughta return the data.

function Profiles() { };

Profiles.prototype.test = function() {
    var returnedResponse;
    var opt = {
        async: false,
        url: __profileurl__+'getall/', type: 'get', dataType:'json',
        success:function(response){
          returnedResponse = response;
        }
    };          
    $.ajax(opt);
    return returnedResponse;
};


但是

除非您真的真的需要立即使用测试的返回值,否则您最好 将回调传递到测试中.像

Unless you really really need to be able to use the return value from test straight away, you'll be much better off passing a callback into test. Something like

Profiles.prototype.test = function(callback) {
    var opt = {
        url: __profileurl__+'getall/', type: 'get', dataType:'json',
        success:function(response){
          callback(response);
        }
    };          
    $.ajax(opt);
};

var profile = new Profiles(); 
profile.test(function(data) {
    // do something with the data
});

这篇关于得到$ .ajax响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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