Dojo使用xhrGet从服务器获取数据并存储在变量中

时间:2013-10-01 12:58:29

标签: javascript dojo

我有以下功能:

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 how to use returned json object? 和: Using hitch / deferred with an xhrGet request 但我仍然无法使用上面的代码获取和存储数据。我不想在xhrGet调用中进行操作,我想检索数据并使用,因为它将被多次使用。

我有什么遗失的吗?

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

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

var deferred = loadMsgBody();
deferred.then(function(response){
  //work with response
});

答案 2 :(得分: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);
        }
    });
}