dojo1.7翻译 ajax功能(Ajax with Dojo)

roodyszz0 2012-04-24

原文地址: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都可以完全的处理这样问题。

定制ajax请求

一个web的开发者要能够使用ajax功能来实现不同的请求任务,要能完成以下功能,但不是只限于这些功能

  • 从服务器中取得静态数据
  • 能处理从服务器中传来的XML或JSON格式的数据
  • 能发送数据到服务器
  • 能对页面进行局部刷新
xhr就可以完成以上的功能。xhr有xhr.get和xhr.post两种方式。我们来看看这两种方法的一些参数。
  • url 要请求的路径
  • handleAs 字符串类型,指要以什么样的格式来处理返回的数据,有"text","json","javascript","xml",默认为"text",如果是"javascript"片断的话会在返回后执行它
  • timeout 超时时间,以毫秒记,如果超时会触发error方法
  • content 以键值对的形式表现的参数,也就是请求参数
  • form 一个有同的参数,通过我们都是使用form来提交的,如果你没有使用url而指定的form,那么将会请求form中的action值,同样,如果你使用了content,那么将会不覆盖form中的参数,所有content/form两者选一个,不要同时使用
上面的参数是来配置怎么发送,对于返回数据的处理有三种方法。
  • load(response,ioArgs) 当请求成功返回值时会调用这个方法。第一个参数是返回值
  • error(errorMessage) 当请求失败时会调用该方法,第一个参数是错误信息
  • handle(response,ioArgs) 不管是成功还是失败都会调用该方法,load或error先调用,然后再调用该方法

示例

刷新节点内容

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 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;
    }
});

 运行示例

什么是JSON

JSON(Javascript Object Notation) 中一种非标准的数据格式,他可以传送复杂的数据结构。结构中可以包括字符串,数字,布尔值,数组和对象。dojo的xhr是支持json格式的。下面就是一个处理json的小例子

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

 运行示例

JSON已经被使用了很多年了,而且大多数的服务端语言都支持对json的加密解密。如php就使用json_encode 和 json_decode方法来处理json数据

JSONP和dojo/io/script

对于基本的ajax功能有一个限制,你不能进行跨域请求。比如你不能在你的服务器中使用xhr.get来请求我的服务器地址。但有另一个方法,你可以使用JSONP。其工作方式为

  • 创建一个script节点
  • 设置script节点的src属性为你要请求的地址,在地址中加入请求参数,还有再加上回调函数名
  • script节点会被加载在DOM中,将触发浏览器的一个局部请求
  • 服务器返回JSON数据,并按约定包装了回调函数
  • 浏览器执行返回的数据,并调用回调函数
使用JSONP的方法在dojo/io/script模块中,这个模块中的get方法和xhr.get方法有着类似的参数属性,只是多了一个callbackParamName的属性,这个属性将执行回调函数,这个回调函数不是你创建的,而是服务器包装的,所以,你要去查看提供这种服务的说明文档。
下面就是从Twitter取值的一个片断
// Require the xhr module
require(["dojo/io/script", "dojo/on", "dojo/dom", "dojo/_base/array", "dojo/domReady!"],
    function(script, on, dom, arrayUtil) {
         
        // Connect the button
        on(dom.byId("getJson"), "click", function() {
             
            // Output message to DOM
            var tweetsHolder = dom.byId("tweetsHolder");
             
            // Use the get method
            script.get({
                // The URL to get JSON from Twitter
                url: "http://search.twitter.com/search.json",
                // The callback paramater
                callbackParamName: "callback", // Twitter requires "callback"
                // The content to send
                content: {
                    q: "@dojo" // Searching for tweets about Dojo
                },
                // The success callback
                load: function(tweetsJson) {  // Twitter sent us information!
                    // Log the result to console for inspection
                    console.info("Twitter returned: ",tweetsJson);
     
                    // Output the tweets to a DOM element
                    // Or output a "no tweets" message
                    var message = "";
     
                    // If there were tweets returned...
                    if(tweetsJson.results && tweetsJson.results.length) {
                        // Start the list
                        message += "<ul>";
                        // For every tweet returned
                        arrayUtil.forEach(tweetsJson.results,function(tweet) {
                            message += "<li>" + tweet.from_user + " said: " + tweet.text + "</li>";
                        });
                        //End the list
                        message += "</ul>";
                    }
                    else { // Output "no tweets" message
                        message = "No tweets about Dojo were available.";
                    }
                    // Output message to DOM
                    tweetsHolder.innerHTML = message;
                },
                // Ooops!  Error!
                error: function() {
                    tweetsHolder.innerHTML = "Error!  Tweets could not be received.";
                }
            });
        });
 
});
 注意:在以上代码中,我们自己并没有创建名叫callback的方法。
所以我们可以很容易的使用JSONP来使用ajax跨域取取值
但我们一定要记住。服务提供者一定要支持JSONP的API,并不是我们在所有的服务器中都能使用dojo/io/script的

最佳实践

  • get方法是用于从服务器简单取值的方法,post是用户发送表单数据或大量数据到服务器的方法
  • 建议使用error的回调函数,不要期望你的ajax请求是肯定成功的
  • 在发送和接收数据的过程中使用console打印到控制台来确保你的数据都是正确的
  • 根据经验,在ajax请求中要给用户一点提示,如一个在加载的图标等

结论

dojo减少了跨域请求的大量的工作量,并且通过dojo/_base/xhr提供了非常简单的API。同时也通过dojo/oi/script提供了跨域方法xhr.get和xhr.post

相关推荐

mmywcoco / 0评论 2020-06-06