我们知道 Dojo 所有的 request 基本都支持 handleAs 这个参数,我们可以传入“json”,“javascript”,“xml”等值,举“json”为例,如果指定 handleAs 为“json”,Dojo 会在我们接收到返回值之
我们知道 Dojo 所有的 request 基本都支持 handleAs 这个参数,我们可以传入“json”,“javascript”,“xml”等值,举“json”为例,如果指定 handleAs 为“json”,Dojo 会在我们接收到返回值之前将纯字符串转化为 JSON 对象。但是,这些是事先设定好的 handleAs 方式,如果我们要自定义 handleAs 方式呢?答案就是 dojo/request/handlers。
清单 45. dojo/request/handlers 简单示例
require(["dojo/request/handlers", "dojo/request", "dojo/dom", "dojo/dom-construct",
"dojo/json",
"dojo/on", "dojo/domReady!"],
function(handlers, request, dom, domConst, JSON, on){
handlers.register("custom", function(response){
var data = JSON.parse(response.text);
data.hello += "!";
return data;
});
on(dom.byId("startButton"), "click", function(){
domConst.place("<p>Requesting...</p>", "output");
request("./helloworld.json", {
handleAs: "custom"
}).then(function(data){
domConst.place("<p>data: <code>" + JSON.stringify(data) + "</code>",
"output");
});
});
});
可以看到,这里我们通过“handlers.register("custom",...)”自定义了一个 handleAs 的方式,然后再 request 的参数里面指定了以这种方式预处理返回数据(handleAs: "custom")。有了这个功能,我们甚至能够很方便的自定义前端和后端的数据交换格式,大大增强我们开发 Web 应用的灵活性。
