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

Dojo Get data from server and store in a variable using xhrGet

本文关键字:存储 xhrGet 变量 服务器 获取 数据 Dojo      更新时间:2023-09-26

我有以下函数:

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 xhr获取如何使用返回的json对象?和:使用挂钩/延迟与 xhrGet 请求但是我仍然无法使用上述代码获取和存储数据。我不想在 xhrGet 调用中进行操作,我想检索数据并使用,因为它将被多次使用。

我缺少什么吗?

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

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

我会尝试更改您的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);
        }
    });
}

试试这个:

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)