Dojo XHR 请求新语法未按预期加载数据



就像标题所说的那样,我正在为dojo/request/xhr使用新的dojo语法,但这似乎不起作用,并在加载数据时引发错误,而具有相同url的旧语法会给出所需的结果。

这是当前无法正确加载数据的语法:

this.get = function (url, loadFunc, errorFunc, handleFunc) {
xhr( url, {
handleAs: 'json'
}).then(function(data){
typeof loadFunc === 'function' ? loadFunc : function () { };
console.log(url+ " load");
console.log(data);
}, function(error){
typeof errorFunc === 'function' ? errorFunc : function () {  };
console.log(url+" error");
console.dir(error);
}, function(handle){
typeof handleFunc === 'function' ? handleFunc : function () { };
console.log(url+" handle");
console.log(handle);
});
};

正如你所看到的,我正在将数据打印到控制台,我得到了正确的数据,但xhr请求抛出了以下错误:

"SyntaxError:意外的令牌o在Object.parse(本机)在l.json(http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:228:250)在m(http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:227:277)在j[作为handleResponse](http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:151:351)位于XMLHttpRequest.e(http://ajax.googleapis.com/ajax/libs/dojo/1.8.1/dojo/dojo.js:154:393)">

虽然以下旧语法非常有效:

this.get = function (url, loadFunc, errorFunc, handleFunc) {
dojo.xhrGet({
url: url,
handleAs: 'json',
load: typeof loadFunc === 'function' ? loadFunc : function () { },
error: typeof errorFunc === 'function' ? errorFunc : function () { },
handle: typeof handleFunc === 'function' ? handleFunc : function () { }
});
};

编辑:

这是我的JSON数据:

{ "assistants" : [ { "assistants" : [ "M 11",
"M 1"
],
"name" : "M X1"
},
{ "assistants" : [ "M 2",
"M 2XX1",
"M 3"
],
"name" : "M 1"
},
{ "assistants" : [ "M 2" ],
"name" : "M 2"
},
{ "assistants" : [  ],
"name" : "M 3"
}
],
"chiefs" : [ { "chief" : "M X1",
"name" : "M 11"
},
{ "chief" : "M 11",
"name" : "M 1"
},
{ "chief" : "M X1",
"name" : "M 2"
},
{ "chief" : "M 744X1",
"name" : "M 3"
}
],
"departments" : [ { "assistants" : [ "M 11",
"M 3",
"M 21"
],
"chief" : "M X1",
"email" : "dg@somedomain.com",
"interim" : [ "M X542",
"M 4"
],
"members" : [ "M 2",
"M 3",
"M 4",
"M 5",
"M X24544"
],
"name" : "Dep1",
"notify" : [ "Dep2",
"M X2",
"M 21"
],
"resp" : "M 21",
"validators" : [ "Dep2",
"M 2",
"M 558"
]
},
{ "chief" : "M 1",
"email" : "admin@somedomain.com",
"members" : [ "M 11",
"M 12"
],
"name" : "Dep3",
"parent" : "Dep1"
},
{ "chief" : "M 11",
"email" : "commercial@somedomain.com",
"members" : [ "M 21",
"M 22"
],
"name" : "Dep4",
"parent" : "Dep1"
}
],
"orgaTestModel" : { "corporation" : "Corporation Sample",
"name" : "Orga Sample 7855"
},
"root" : "Dep1"
}

注意:我使用的是dojo 1.8.1版本,但我也用dojo 1.9.2进行了测试,但它仍然不起作用。

我搞不清出了什么问题。是我的代码出了问题,还是其他问题?

如有任何帮助,我们将不胜感激。

您还没有提供原始JSON响应的示例,但我猜它不是有效的JSON。

handleAs设置为"json"时,dojo.xhrGet实际上使用eval,根据定义,这将比严格的JSON解析器更宽松。另一方面,dojo/request使用JSON.parse(如果可用),这要求JSON格式良好(例如,所有键都是带引号的字符串,所有字符串都使用双引号)。

尝试将一个JSON响应粘贴到http://jsonlint.org/-如果它没有在那里进行验证,那么它就不会使用dojo/request进行验证。

(dojo.xhrGet之所以使用eval,尽管它可能不安全,是因为它是在广泛支持JSON.parse之前编写的,更改它会破坏向后兼容性——换句话说,即使不切换API,开发人员也会遇到你现在遇到的问题。)

编辑:问题中提供的JSON现在是有效的,可以与旧的和新的API一起使用。

最新更新