1

我有以下功能:

loadMsgBody: function (id) {
    return dojo.xhrGet({
        url: "myurl",
        handleAs: "text",
        content: {
            id: id
        },
        load: function (response) {
            return response;
        },
        error: function (response) {
            alert(response);
        }
    });
}

并称它为:

var text = "";
this.loadMsgBody(this.msgId).then(function (response) {
    text = response;
});

现在我希望得到函数的返回值,但我得到的是一个空的文本值。但是,在 Firebug 中,我确实看到来自服务器的响应具有正确的值。我搜索并找到了这些链接:DOJO xhrGet 如何使用返回的 json 对象? 并且: 使用hitch / deferred和xhrGet请求 但是我仍然无法使用上面的代码获取和存储数据。我不想在 xhrGet 调用中进行操作,我想检索数据并使用它,因为它将被多次使用。

有什么我想念的吗?

4

3 回答 3

0

我会尝试改变你的load功能来唤起你的callback功能:

loadMsgBody: function (id, callback) {
    return dojo.xhrGet({
        url: "myurl",
        handleAs: "text",
        content: {
            id: id
        },
        load: function (response) {
            if(callback) {
                callback(response);
            }
        },
        error: function (response) {
            alert(response);
        }
    });
}
于 2013-10-01T14:00:02.533 回答
0

Dojo 的 XHR 方法返回类dojo/Deferred的实例,因为它们是异步的。这意味着函数在响应的值可用之前返回。为了使用异步响应的结果,您需要等待它返回。Dojo 使用统一的 API Deferreds 公开了这一点。类的实例dojo/Deferred有一个方法then。该then方法将函数作为参数。一旦 Deferred 被解决(在这种情况下,当请求完成时),该函数将执行。

var deferred = loadMsgBody();
deferred.then(function(response){
  //work with response
});
于 2013-10-01T13:58:21.940 回答
0

尝试这个:

loadMsgBody: function (id, callback) {
    return dojo.xhrGet({
        url: "myurl",
        handleAs: "text",
        content: {
            id: id
        },
        load: function (response) {
            callback.apply(null,[response]);
        },
        error: function (response) {
            alert(response);
        }
    });
}

然后:

var text = "";
this.loadMsgBody(this.msgId, function (response) {
    text = response;
    console.log("text:",text);  // this will show your return data

});

 console.log("text:",text);  // this will show empty data because ajax call is asynchrize, at this time , data not return yet.

 setTimeout(function(){
    console.log("text:",text);  // this will show your return data again because ajax call should have finished after 30000 ms 
 },30000)
于 2013-10-01T13:38:30.863 回答