日期:2014-05-16 浏览次数:20870 次
原文地址:http://dojotoolkit.org/documentation/tutorials/1.7/ajax/
?
Ajax是一个动态网站的基本功能,在这个教程中,你将会学到如何使用dojo的ajax使用方法,包括了基本的XHR连接,自定义回调函数,处理多类型数据和使用json跨域取值。
?
由于在dojo,dijit,dojox的多个组件和类中都要用到ajax功能,所以dojo就把ajax方法放到了dojo base类中。但是在操作使用ajax时他的依赖类还是要被指定的。ajax工具类被放置于dojo/_base/xhr这个模块中。下面是示例
?
// 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地址中请求数据,如果取值成功将会把返回的信息alert出来。如果取值出问题会怎么样?又或者返回的数据是json或xml格式的我们可以怎么处理?还有,我想要提交一个form的数据将怎么办?xhr都可以完全的处理这样问题。
?
一个web的开发者要能够使用ajax功能来实现不同的请求任务,要能完成以下功能,但不是只限于这些功能
?
刷新节点内容
?
?
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
            }
        });
         
});
?
运行示例
?
检查用户名是否可用
?
// 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.";
        }
    }
});
?
?运行示例
?
form提交
?
// Local var representing if the form has been sent at all
var hasBeenSent = false;
 
// Local var representing node