从jQuery promise对象返回数据

时间:2013-03-11 10:57:20

标签: jquery getjson promise

我正在使用$.getJSON()并尝试使用以下各种代码返回数据:

 var changeUserPage = function (id) {
       return repository.getUserPage(id).done(function (data) {            
           // console.log(data)
       })
 }

问题是虽然在done函数内部,我可以看到我想要的正确数据,但我无法将其返回给我的调用函数,如:

 var data = dataContext.changeUserPage(lastPolicyWorkedOn);

数据当前持有promise对象:

Object {readyState: 1, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}

修改

getJSON方法如下所示:

var getUserPage = function (policyId) {
       policyId = encodeURIComponent(policyId);

       var uri = "http://localhost:54997/api/policy/getUserPage/" + policyId;
       return $.getJSON(uri);         
}

如何最好地返回实际的json数据?

由于

戴维

1 个答案:

答案 0 :(得分:2)

changeUserPage无法返回数据,因为数据是使用async方法$.getJSON获取的。

更改

var data = dataContext.changeUserPage(lastPolicyWorkedOn);

dataContext.changeUserPage(lastPolicyWorkedOn).done(function(data){
    //do something with data
});
相关问题