Ajax with Dojo

  http://dojotoolkit.org/documentation/tutorials/1.7/ajax/  官方

  http://www.ibm.com/developerworks/cn/web/wa-lo-dojointro2/    IBM

  http://www.infoq.com/cn/articles/dojo-ajax-xhr/

  由于很多类和小部件中使用Dojo,Dijit,DojoX都用到了Ajax,所以Dojo Toolkit讲Ajax方法烤到dojo/base当中。

  然而,当在毫无根据的运营模式(operating in baseless mode)通过指定异步:适用于data-dojo-config,所有依赖项都必须显式地请求。However, when operating in baseless mode (by specifying async: true in data-dojo-config), all dependencies must be requested explicitly.

// Require the xhr module
require(["dojo/_base/xhr"],
    function(xhr) {     
        // Execute a HTTP GET request
        xhr.get({
            // The URL to request
            url: "get-message.php",
            // The method that handles the request's successful result
            // Handle the response any way you'd like!
            load: function(result) {
                alert("The message is: " + result);
            }
        });        
});

  上面的代码执行一个Ajax请求get-message.php。通过我们指定的加载函数它,返回一个纯文本消息和警报给用户。

  如果有什么错误呢?或XML或JSON响应?如果我们想要发送表单数据到服务器?没问题——xhr支持完整的请求定制和管理。

  The code above executes an Ajax request to get-message.php, which returns a plain text message and alerts it to the user via the load function we specified. What if there's an error though? Or the response is XML or JSON? What if there's form data we want to send to the server? No problem —xhr allows for complete request customization and management.

  自定义Ajax请求:Customizing an Ajax Request

  • Loading static data from the server
  • Accessing XML or JSON data from a web service
  • Sending form data to the server
  • Refreshing content on a page

 相关参数:

  • url:请求发送的地址
  • handleAs:返回结果的数据类型,决定了如何对服务器返回的数据进行预处理
  • timeOut:请求响应的时间,如果超出时间则自动执行error方法
  • content:发送到服务器端的数据,键值对形式 {a:"b",c:"d"}
  • form:发送的表单形式,与content不能同时存在‘
  • load(response, ioArgs):服务器相应处理成功后调用
  • error(errorMessage):服务器相应处理出现错误时调用
  • handle(response, ioArgs):无论成功还是失败都会调用
  • response:表示从服务器端返回的数据,Dojo 已经根据 handleAs 设置的数据类型进行了预处理。
  • ioArgs: 这是一个对象,包含调用 xhrGet 时使用的一些参数。之所以把这些信息放在一个对象中并传递给回调函数是为了给回调函数一个执行“上下文”,让回调函数知道自己属于哪个 HTTP 请求,请求有哪些参数,返回的数据是什么类型等。这些信息在调试程序时特别有用。
    • ioArgs.url:请求的 URL,与调用 xhrGet 时设置的值一样。
    • ioArgs.query:请求中包含的参数, URL 中“ ? ”后面的内容。
    • ioArgs.handAs:如何对返回的数据进行预处理,与调用 xhrGet 时设置的值一样。
    • ioArgs.xhr: xhrGet 函数使用的 XHR 对象。
  • 表 1 handleAs VS 预处理方式
    handleAs 预处理方式
    text 默认值,不对返回的数据做任何处理
    xml 返回 XHR 对象的 responseXML
    javascript 使用 dojo.eval 处理返回的数据,返回处理结果
    json 使用 dojo.fromJSon 来处理返回的数据,返回生成的 Json 对象
    json-comment-optional 如果有数据包含在注释符中,则只使用 dojo.fromJSon 处理这部分数据,如果没有数据包含在注释符中,则使用 dojo.fromJSon 处理全部数据。
    json-comment-filtered 数据应该包含在 /* … */ 中,返回使用 dojo.fromJSon 生成的 Json 对象,如果数据不是包含在注释符中则不处理。

    假设 handleAs 被设置为“ json ”,按照上表,则 load 回调函数的参数 response 为 JSON 对象。如果 handleAs 不是“ json ”,还能不能生成 JSON 对象呢?答案是肯定的,可以把 handleAs 设为“ text ”,那么返回的是普通的字符串,只要字符串是 JSON 对象的文本形式,则可以简单地使用 eval() 函数把它转换为真正的 JSON 对象,而不再需要任何其他的 API 完成转换工作。

  • function jsonDemo() { 
        response = (
            "[{ name: 'Joe', age: '30', gender: 'M'}, 
            { name: 'Chandler', age: '32', gender: 'M'}, 
            { name: 'Rose', age: '31', gender: 'M'}]"
        ); 
        json = eval(response); 
        document.write(json[0].name + "," + json[1].age + 
            "," +  json[2].gender); 
    }

     

  示例1:

require(["dojo/_base/xhr", "dojo/dom", "dojo/domReady!"],
    function(xhr, dom) {
         
        // Using xhr.get, as very little information is being sent
        xhr.get({
            // The URL of the request
            url: "get-content.php",
            // The success callback with result from server
            load: function(newContent) {
                dom.byId("contentNode").innerHTML = newContent;
            },
            // The error handler
            error: function() {
                // Do nothing -- keep old content there
            }
        });
         
});

  示例2:

// 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.";
        }
    }
});

  示例3:

// Local var representing if the form has been sent at all
var hasBeenSent = false;
 
// Local var representing node to be updated
var messageNode = dom.byId("messageNode");
 
// Using xhr.post, as the amount of data sent could be large
xhr.post({
    // The URL of the request
    url: "submission.php",
    // No content property -- just send the entire form
    form: dom.byId("contactForm"),
    // The success handler
    load: function(response) {
        messageNode.innerHTML = "Thank you for contacting us!";
    },
    // The error handler
    error: function() {
        messageNode.innerHTML = "Your message could not be sent, please try again."
    },
    // The complete handler
    handle: function() {
        hasBeenSent = true;
    }
});

示例4:

require(["dojo/_base/xhr", "dojo/dom", "dojo/_base/array", "dojo/domReady!"],
    function(xhr, dom, arrayUtil) {
         
        // Keep hold of the container node
        var containerNode = dom.byId("newsContainerNode");
         
        // Using xhr.get, as we simply want to retrieve information
        xhr.get({
            // The URL of the request
            url: "get-news.php",
            // Handle the result as JSON data
            handleAs: "json",
            // The success handler
            load: function(jsonData) {
                // Create a local var to append content to
                var content = "";
                // For every news item we received...
                arrayUtil.forEach(jsonData.newsItems, function(newsItem) {
                    // Build data from the JSON 
                    content += "<h2>" + newsItem.title + "</h2>";
                    content += "<p>" + newsItem.summary + "</p>";
                });
                // Set the content of the news node
                containerNode.innerHTML = content;
            },
            // The error handler
            error: function() {
                containerNode.innerHTML = "News is not available at this time."
            }
        });
         
});

 

posted @ 2014-01-22 14:01  刘朝样  阅读(174)  评论(0)    收藏  举报