0

我正在尝试在 Dojo 中组织我的代码,但我不了解事情是如何工作的。我想在 REST 调用后捕获 json 数据,但它不起作用。我分配 REST 返回的testJson属性始终为 NULL。

我怎样才能做到这一点?我在下面复制了我当前的代码。(我想在 ClassDAO 和 Controller 中使用我的代码。

define([
    'dojo/_base/declare',
    'dojo/request/xhr'
], function (declare, xhr) {

    return declare(null, {


        testJson: null,

        constructor: function(){

        },

        get: function(){

            xhr('/rest/reports', {
                method: 'get',
                handleAs: 'json',
                headers: {
                    Accept: 'application/json'
                }

            }).then(function(jsonData){

                    testJson = jsonData;

                }, function(err){
                    alert(err);
                }, function(evt){
                    // Handle a progress event from the request if the
                    // browser supports XHR2
                });

        }

    });
});
4

1 回答 1

0

看起来您正在尝试将类属性设置为变量;因此,

testJson = jsonData;

必定是:

this.testJson = jsonData

否则,您实际上是在设置全局变量 testJson,而不是属性。您还需要将then()函数的范围限定为您的类:

.then(lang.hitch(this, function(jsonData){
    this.testJson = jsonData;
}))

lang对象是dojo/_base/lang并且需要添加到define()

define([
    "dojo/_base/declare",
    "dojo/request/xhr",
    "dojo/_base/lang"
], function (declare, xhr, lang) {

作用域是 Javascript 的一个重要概念,过去曾让我们感到困惑。有关更多详细信息,请参阅hitch()命令的文档。

于 2012-11-15T22:18:04.247 回答