原文地址: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 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(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数据
对于基本的ajax功能有一个限制,你不能进行跨域请求。比如你不能在你的服务器中使用xhr.get来请求我的服务器地址。但有另一个方法,你可以使用JSONP。其工作方式为
// 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."; } }); }); });
dojo减少了跨域请求的大量的工作量,并且通过dojo/_base/xhr提供了非常简单的API。同时也通过dojo/oi/script提供了跨域方法xhr.get和xhr.post