官方的例子需要访问一个json文件,内容如下:
[
{ "id": 1, "username": "user1", "name": "User One" },
{ "id": 2, "username": "user2", "name": "User Two" },
{ "id": 3, "username": "user3", "name": "User Three" }
]
放在服务器上,和html文件放在一起就可以了。
例子1是比较繁琐的创建和使用deferred:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo: dojo/Deferred</title>
<link rel="stylesheet" href="css/style.css" media="screen">
</head>
<body>
<h1>Demo: dojo/Deferred</h1>
<ul id="userlist"></ul>
<!-- load dojo and provide config via data attribute -->
<script src="dojo/dojo.js" data-dojo-config="isDebug: 1, async: 1, parseOnLoad: 1"></script>
<script>
require(["dojo/Deferred", "dojo/request", "dojo/_base/array", "dojo/dom-construct", "dojo/dom", "dojo/domReady!"],
function(Deferred, request, arrayUtil, domConstruct, dom) {
var deferred = new Deferred(),
userlist = dom.byId("userlist");
deferred.then(function(res){
arrayUtil.forEach(res, function(user){
domConstruct.create("li", {
id: user.id,
innerHTML: user.username + ": " + user.name
}, userlist);
});
},function(err){
domConstruct.create("li", {
innerHTML: "Error: " + err
}, userlist);
});
// Send an HTTP request
request.get("users.json", {
handleAs: "json"}).then(
function(response){
// Resolve when content is received
deferred.resolve(response);
},
function(error){
// Reject on error
deferred.reject(error);
}
);
});
</script>
</body>
</html>
例子2是:一般的用法,实际中的用法:
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo: dojo/Deferred with dojo/request</title>
<link rel="stylesheet" href="css/style.css" media="screen">
</head>
<body>
<h1>Demo: dojo/Deferred with dojo/request</h1>
<ul id="userlist"></ul>
<!-- load dojo and provide config via data attribute -->
<script src="dojo/dojo.js" data-dojo-config="isDebug: 1, async: 1, parseOnLoad: 1"></script>
<script>
require(["dojo/request", "dojo/_base/array", "dojo/dom-construct", "dojo/dom", "dojo/domReady!"],
function(request, arrayUtil, domConstruct, dom) {
var deferred = request.get("users.json", {
handleAs: "json"
});
deferred.then(function(res){
var userlist = dom.byId("userlist");
arrayUtil.forEach(res, function(user){
domConstruct.create("li", {
id: user.id,
innerHTML: user.username + ": " + user.name
}, userlist);
});
},function(err){
// This shouldn't occur, but it's defined just in case
alert("An error occurred: " + err);
});
});
</script>
</body>
</html>
明显例子2更好一下,效果一样一样的。

博客介绍了官方示例中需访问的json文件内容,给出两个dojo/Deferred使用示例。例子1繁琐地创建和使用deferred,例子2是一般实际用法。通过对比可知,例子2效果相同但更优。
385

被折叠的 条评论
为什么被折叠?



