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

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

下面例子都使用了 JSON 数据。

提供了一个简单的 JSONP 示例。正如您所看到的,通过使用一个回调参数,可以避免将 XHR 完全地简单附加到脚本中。返回给回调,并在可执行 JavaScript 代码中包装数据对象。

JSONP 数据

var callback = function( data ) {
 document.getElementById("main").innerHTML += "<p>"+ data.sample.txt +"</p>";
}
var jsonpSample = function(e){
//create a script element
 var jsonp = document.createElement("script");
//give it a source with the callback name appended in the query string
 jsonp.src= "_assets/data/jsonp.do?callback=callback";
//add it to the doc
 document.body.appendChild(jsonp);
 e.preventDefault();
}
//wire up the event
document.getElementById("activate").addEventListener("click", jsonpSample, false);

库示例

对于大多数开发人员来说,只有进行学术研究的人才会对 Ajax 请求的本质感兴趣。大多数实际工作是在一个或多个 JavaScript 库中完成。除了修补跨浏览器不兼容性,这些库都提供了构建于基础 API 之上的特性。下列示例展示了 3 个流行库中的 GET 和 POST 示例来介绍不同的 API。

jQuery

让我们从流行 jQuery 库开始举例说明。jQuery 的 Ajax 函数最近进行了重写,将几个高级功能包含在内,这不是术语本文的讨论范围,但是所有 jQuery Ajax 请求的常见功能都以传递给该函数的配置对象的参数形式存在。另外还要注意的是,jQuery 有几个便利的方法,比如 $.post 和$.get,这是常见请求配置的快捷键。
展示了使用 jQuery 获取数据的简要代码。

一个 jQuery GET 请求

/*
callback is a simple function that will be run
when the data is returned from the server
*/
var callback = function( data ) {
/* 
it just adds a little bit of text to the document
data is the JSON object returned by the server. 
*/
 $("#main").append($("<p />").text(data.sample.txt));
}
/*
Wire up the ajax call to this click event
*/
$("#activate").click(
 function(){
//call $.ajax with a configuration object 
 $.ajax({
//it's just a get request
  type: 'get',
//we're looking for this URL 
  url: '_assets/data/json-1.json',
//Our cool callback function
  success: callback,
//it's going to be JSON 
  dataType: "json"
 })
 } 
)

下面演示了如何发布和检索简单 JSON 对象。需要注意的是,这里使用了原生 JSON 对象来分析输入数据。jQuery 文档明确提及需要通过 JSON2.js 脚本增加不受支持的浏览器。

提供一个显式错误句柄使得成功请求和失败请求都能得到优雅的处理。jQuery 的错误状态带有 3 个参数,包括 XHR 对象本身,这支持健壮的错误处理。

一个 jQuery POST

/*
this is the object we're going to post
*/
var myMessages = {
 positive : "Today is a good day",
 negative : "Today stinks",
 meh : "meh"
}
var callback = function( data ) {
 $("#main").append($("<p />").text(data.positive));
}
/*
Setting up a simple error handler.
It doesn't do much. 
It's just nice to illustrate error handling.
*/
var errorHandler = function( xhr, textStatus, errorThrown ){
 throw new Error("There was an error. The error status was " + textStatus );
}
/*
Here's where the action happens.
Attach an event to out simple button.
*/
$("#activate").click(
 function(){
//call $.ajax with a configuration object 
  $.ajax({
   //we're sending data to the server  
   type: 'POST',
   //this is our URL
   url: '_assets/data/post-responder.do',
   /*
   This is our data, JSON stringified
   jQuery expects to use native JSON
   or JSON2.js in unsupported browsers
   */
   data: JSON.stringify(myMessages),
   //Here's where we set up our callback function
   success: callback,
   //The data expected from the server
   dataType: "json",
   //And our simple error handler
   error : errorHandler
   }
  )
 }
);