ajax详解_动力节点Java学院整理

2019-09-14 06:47:20王冬梅

Dojo

Dojo 不仅仅是下列示例中演示的简单 Ajax 请求/DOM 操作。它实际上是为硬核应用程序开发而构建的。这就是说,以这种方式查看 API 仍然是值得期待的。

注意两个独立的 “Ajax” 函数:xhrGet 和 xhrPost。另外还要注意的是,这里使用了 Dojo JSON 实用函数来分析输入数据。下面 展示了一个 GET 示例。

一个 Dojo GET 请求

var callback = function( data ) {
//note the document.getelementById alias
 dojo.byId("main").innerHTML += "<p>"+ data.sample.txt +"</p>";
}
var getData = function(){
//xhrGet is for get requests
dojo.xhrGet({
 //the URL of the request
 url: "_assets/data/json-1.json",
 //Handle the result as JSON data
 handleAs: "json",
 //The success handler
 load: callback
});
}
// Use connect to attach events
dojo.connect( dojo.byId("activate"), "onclick", getData );

下面展示了一个 Dojo POST,包含一个错误句柄的配置。

Dojo POST

var myMessages = {
 positive : "Today is a good day",
 negative : "Today stinks",
 meh : "meh"
}
var callback = function( data ) {
 dojo.byId("main").innerHTML += "<p>"+ data.positive +"</p>";
}
var errorHandler = function(){
 throw new Error("We dun goofed.")
}
var postData = function(){
 //not surprisingly xhrPost is for POST
 dojo.xhrPost({
  // The URL of the request
  url: "_assets/data/post-responder.do",
  //This will be JSON
  handleAs: "json",
  //Set the headers properly
  headers: { "Content-Type": "application/json; charset=uft-8"},
  //Use Dojo's JSON utility
  postData: dojo.toJson(myMessages),
  // The success handler
  load: callback,
  // The error handler
  error: errorHandler
 });
}
// Use connect to attach events
dojo.connect( dojo.byId("activate"), "onclick", postData );

Yahoo! 用户界面 (YUI)

YUI 库提供一个与前面两个略有不同的模式。首先,YUI 返回整个 XHR 对象,不仅解析数据,还允许更准确地操作返回数据和整个请求的可见性。这也意味着开发人员需要了解 XHR 对象的来龙去脉。另外,这里还展示了 YUI 模块加载程序 use() 的使用,需要注意的是,即使与 Ajax 没有直接联系(除了加载 io 模块之外)。中有一个 YUI 模块列表,还有一个用作参数的回调函数。一旦运行,就可以从 Yahoo! Content Delivery Network (CDN) 下载数据包,Yahoo! Content Delivery Network (CDN) 包含单个基于 CDN 的下载包中所需的所有模块。

一个 YUI GET 请求

// Create a new YUI instance and populate it with the required modules.
YUI().use('node','event', 'json', 'io', function (Y) {
 var callback = function( id, xhr ) {
  var data = Y.JSON.parse(xhr.responseText);
  Y.one('#main').append("<p>" 
   + data.sample.txt 
   +"</p>");
 }
 Y.one("#activate").on('click',
  function(){
   Y.io( '_assets/data/json-1.json', {
   //This is actually the default
   method: 'get',
   on:  {success: callback}
   })
  } 
 )
});