dojo 十 ajax dojo/_base/xhr

官方教程:Ajax with Dojo
Ajax功能:
1.从服务器加载静态数据
2.从web服务中访问xml或json类型的数据
3.将表单(form)数据发送到服务器
4.刷新页面内容
。。。。
Ajax在RIA中是核心技术,下面来看看Dojo是如何运用它的。

 // Require the xhr module
require(["dojo/_base/xhr", "dojo/dom"],
    function(xhr,dom) {

// Local var representing the node to be updated
var availabilityNode = dom.byId("availabilityNode");
// Using xhr, as very little information is being sent
xhr.get({
    // The URL of the request
    url: "check-username.php",
    // Allow only 2 seconds for username check
    timeout: 2000,
    // Send the username to check base on an INPUT node's value
    content: {
        username: dom.byId("usernameInput").value.toLowerCase()
    },
    // The success callback with result from server
    load: function(result) {
        if(result == "available") {
            availabilityNode.innerHTML = "Username available!";
        }
        else {
            availabilityNode.innerHTML = "Username taken!  Please try another.";
        }
    },
   
// The error handler
    error: function(errorMessage){
        alert(errorMessage);
    }
,
    // The complete handler
    handle: function() {
        hasBeenSent = true;
    }
});
});


首先要引入包dojo/_base/xhr。
然后通过调用xhr.get或xhr.post这两个常用的方法来发送请求。
这两个方法的参数是一个对象,包含以下属性:
url:请求的服务器地址
handleAs:返回数据的格式,默认为"text",可选"json","javascript"(加载并执行),"xml"
timeout:请求超时,以毫秒记算,当超过这个时间视为请求失败并触发error处理函数
content:请求时发送的内容,是一个“键-值”对形式的对象。如果调用的是get方法,会被转换为一个字条串,如果是post方法,则转换为post内容体。
form:指定一个表单节点对象,将会发送表单内所有的数据,此时如果没有指定url,将会采用form属性action的值,如果同时设置content将会覆盖form中的内容,不建议同时使用

当服务器接受到请求并做出回应后,可以通过以下三个方法来处理:
load(response, ioArgs):请求成功时的回调函数,第一个参数就是根据handleAs指定的格式返回的数据内容。
error(errorMessage) :请求失败时的回调函数,数据为失败的信息
handle(response, ioArgs) :不论成功或失败都将调用的回调函数
根据请求是否成功,首先会调用load/error函数,然后调用handle

JSON数据结构
JSON是以“键-值”对为单位的数据结构,如{"name":"mqsy_yj", "age":30,"ismale",true},键为"name",值为"mqsy_yj"。
“键-值”对之间用逗号分隔,大括号为一个JSON对象,多个JSON对象用逗号分隔并包含在一个中括号内为一个JSON对象数组。
在dojo中对JSON的处理方法为:
require(["dojo/_base/array"],function(array){
    var jsonData = {"newsItems":[{"name":"mqsy_yj", "age":30,"ismale",true},{"name":"mqsy_yj1", "age":31,"ismale",false}]};
    var content = "";

                // For every news item we received...
                arrayUtil.forEach(jsonData.newsItems, function(newsItem) {
                    // Build data from the JSON
                    content += "<h2>" + newsItem.name+ "</h2>";
                    content += "<p>" + newsItem.age+ "</p>";
                    content += "<p>" + newsItem.ismale+ "</p>";
                });



});

posted @ 2013-11-09 18:03  JackGIS  阅读(650)  评论(0)    收藏  举报