jayleke

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

在使用jquery的时候,我们经常用到jquery中对ajax的封装,下面对ajax函数的各参数详细说明和讲解,以便更好的理解和使用 $.get(url, data, callback,type) 和 $.post(url, data, callback, type).

 

1、 jQuery.ajax( options ) : 通过 HTTP 请求加载远程数据

这个是jQuery 的底层 AJAX 实现。简单易用的高层实现见 $.get, $.post 等。

$.ajax() 返回其创建的 XMLHttpRequest 对象。大多数情况下你无需直接操作该对象,但特殊情况下可用于自己控制提交的参数和HTTP Header的设定。

注意: 如果你指定了 dataType 选项,请确保服务器返回正确的 MIME 信息,(如 xml 返回 "text/xml")。错误的 MIME 类型可能导致不可预知的错误。见 Specifying the Data Type for AJAX Requests 。
当设置 datatype 类型为 'script' 的时候,所有的远程(不在同一个域中)POST请求都回转换为GET方式。

$.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数信息。详细参数选项见下。

jQuery 1.2 中,您可以跨域加载 JSON 数据,使用时需将数据类型设置为 JSONP。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。数据类型设置为 "jsonp" 时,jQuery 将自动调用回调函数。(这个我不是很懂)

参数列表:

 

参数名 类型 描述
url String (默认: 当前页地址) 发送请求的地址。
type String (默认: "GET") 请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。
timeout Number 设置请求超时时间(毫秒)。此设置将覆盖全局设置。
async Boolean (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
beforeSend Function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。
function (XMLHttpRequest) {
this; // the options for this ajax request }
cache Boolean (默认: true) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息。
complete Function 请求完成后回调函数 (请求成功或失败时均调用)。参数: XMLHttpRequest 对象,成功信息字符串。
function (XMLHttpRequest, textStatus) {
this; // the options for this ajax request }
contentType String

(默认: "application/x-www-form-urlencoded") 发送信息至服务器时内容编码类型。默认值适合大多数应用场合。告诉服务器从浏览器提交过来的数据格式。

例如:我们提交数据时假如使用了 JSON2.js 中方法 JSON.stringify(obj) 格式化为json字符串后,再默认提交就会报错。这个时候就需要指定提交的内容格式为:"application/json"。

data Object,
String

发送到服务器的数据。

若data数据类型为JavaScript对象或数 组,Jquery在提交之前自动调用JQuery.param()方法把要发送的数据编码成为"application/x-www-form- urlencoded"格式的数据(即 name=value&name1=value1);JavaScript对象必须为 Key/Value 格式;如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2';

若data数据类型为String类型,则直接默认该数据已经按照"application/x-www-form-urlencoded"格式编码完成,不再转换。

processData选项可以控制是否进行转换。该选项默认为true。

dataType String

预期服务器返回的数据类型。设定HttpHeader中“Accept”域的内容,告诉服务器浏览器可以想要返回的数据格式类型,同时JQuery也会根据该类型对返回的数据进行处理。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息返回 responseXML 或 responseText,并作为回调函数参数传递,可用值:

"xml": 返回 XML 文档,可用 jQuery 处理。

"html": 返回纯文本 HTML 信息;包含 script 元素。

"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。

"json": 返回 JSON 数据 。JQuery将返回的字符串格式数据自动转化为Javascript对象,便于直接使用obj.property格式访问。若没有指定该选项,即使返回的是JSON格式的字符串,JQuery也不会自动转换。

"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

error Function (默认: 自动判断 (xml 或 html)) 请求失败时将调用此方法。这个方法有三个参数:XMLHttpRequest 对象,错误信息,(可能)捕获的错误对象。
function (XMLHttpRequest, textStatus, errorThrown) {
// 通常情况下textStatus和errorThown只有其中一个有值 this; // the options for this ajax request }
global Boolean (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 。可用于控制不同的Ajax事件
ifModified Boolean (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。
processData Boolean (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
success Function 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态
function (data, textStatus) {
// data could be xmlDoc, jsonObj, html, text, etc... this; // the options for this ajax request }

 

这里有几个Ajax事件参数:beforeSend ,success ,complete ,error 。我们可以定义这些事件来很好的处理我们的每一次的Ajax请求。注意一下,这些Ajax事件里面的 this 都是指向Ajax请求的选项信息的(请参考说 get() 方法时的this的图片)。
请认真阅读上面的参数列表,如果你要用jQuery来进行Ajax开发,那么这些参数你都必需熟知的。

示例代码,获取博客园首页的文章题目:

 1 $.ajax({
 2  type: "get",
 3  url: "http://www.cnblogs.com/rss",
 4  beforeSend: function(XMLHttpRequest){
 5  //ShowLoading(); }, success: function(data, textStatus){
 6  $(".ajax.ajaxResult").html("");
 7  $("item",data).each(function(i, domEle){
 8  $(".ajax.ajaxResult").append("<li>"+$(domEle).children("title").text()+"</li>");
 9  });
10  },
11  complete: function(XMLHttpRequest, textStatus){
12  //HideLoading(); }, error: function(){
13  //请求出错处理 } });

为了说明 contentType: "application/json" 和 dataType:"JSON"选项,JQuery对返回数据进行了自动转化,下面举个例子:

 前段页面: register.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"%>  
 2 <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>  
 3 <%  
 4 String webProject = request.getContextPath();  
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";  
 6 %>  
 7   
 8 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
 9 <html>  
10 <head>  
11 <base href="<%= basePath %>" />  
12 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
13 <title>User Register Page</title>  
14 <script type="text/javascript" src="<%=webProject%>/resource/js/jquery-1.7.2.min.js"></script>  
15 <script type="text/javascript" src="<%=webProject%>/resource/js/json2.js"></script><style type="text/css">  
16 .error{  
17     color: red;   
18 }  
19 </style>  
20 <script type="text/javascript">  
21     function register(){  
22         var params={  
23                 "userName": $("#userName").val(),  
24                 "password": $("#password").val(),  
25                 "email"   : $("#email").val()  
26                 };  
27         var url = "<%=webProject%>/register";  
28         var successFun = function(data, textStatus){  
29                     alert("success!");  
30                     alert("responseText="+data.userName);  
31                     alert("statusText="+textStatus);  
32                 };  
33         var errorFun = function (XMLHttpRequest, textStatus, errorThrown) {  
34             alert("error");  
35             alert("XMLHttpRequest="+XMLHttpRequest);  
36             alert("statusText="+textStatus);  
37             alert("errorThrown="+errorThrown);  
38              }  
39         $.ajax({  
40             type: "POST",  
41             url : "<%=webProject%>/register",  
42             data: JSON.stringify(params),  
43             success: successFun,  
44             error: errorFun  
45             //contentType: "application/json",  
46             //dataType: "json"            
47         });  
48     }     
49 </script>  
50 </head>  
51   
52 <body>      
53     <sf:form method="post" modelAttribute="user">  
54         <p>用户注册页面:</p>  
55         <table width="60%" align="center">  
56             <colgroup>  
57                 <col width="10%" align="right" />  
58                 <col />  
59             </colgroup>     
60             <tr>  
61                 <th>用户名:</th>  
62                 <td>  
63                     <sf:input path="userName" />  
64                     <small>length of userName is not more than 20.</small><br />  
65                     <sf:errors path="userName" cssClass="error"/>  
66                 </td>  
67             </tr>  
68             <tr>  
69                 <th>密码:</th>  
70                 <td>  
71                     <sf:password path="password" />  
72                     <small>length of password is not less than 6.</small><br />  
73                     <sf:errors path="password" cssClass="error" />  
74                 </td>  
75             </tr>  
76             <tr>  
77                 <th>邮箱:</th>  
78                 <td>  
79                     <sf:input path="email"/>  
80                     <small>format should confirm to general standard.</small><br />  
81                     <sf:errors path="email" cssClass="error" />  
82                 </td>  
83             </tr>               
84             <tr>  
85                 <td colspan="2" align="center">  
86                     <input type="button" value="注册" onclick="register()"/>  
87                 </td>  
88             </tr>  
89         </table>  
90     </sf:form>  
91 </body>  
92 </html>  

服务器端代码:

 1 package org.study.controller;  
 2   
 3 import java.io.IOException;  
 4   
 5 import javax.servlet.http.HttpServletResponse;  
 6   
 7 import org.springframework.stereotype.Controller;  
 8 import org.springframework.ui.Model;  
 9 import org.springframework.web.bind.annotation.RequestMapping;  
10 import org.springframework.web.bind.annotation.RequestMethod;  
11 import org.study.domain.User;  
12   
13 /**  
14  * 用户注册、登陆相关信息的Controller。  
15  * 使用JSON方式处理输入和输出数据。  
16  *   
17  * @author CHEN Dezong  
18  * @version 1.0.0  
19  *  
20  */  
21 @Controller  
22 @RequestMapping ("/register")  
23 public class RegisterController {  
24       
25     /**  
26      * 显示用户注册页面。  
27      * @param model  
28      * @return  
29      */  
30     @RequestMapping (method = RequestMethod.GET)  
31     public String showRegister(Model model){  
32         model.addAttribute(new User());  
33           
34         return "register";  
35     }  
36       
37     /**  
38      * 处理提交的用户注册信息。  
39      * @param model  
40      * @return  
41      * @throws IOException   
42      */  
43     @RequestMapping (method = RequestMethod.POST)  
44     public void doRegister(HttpServletResponse response) throws IOException{  
45           
46         String value = "{'userName':'中文', 'password':'123'}";  
47           
48         response.setCharacterEncoding("UTF-8");  
49 //      response.setHeader("content-type", "application/json");  
50           
51         response.getWriter().print(value);  
52         response.getWriter().close();  
53     }  
54       
55 }  

POJO 对象 User.java

 1 package org.study.domain;  
 2   
 3 public class User {  
 4     private String userName;  
 5       
 6     private String password;  
 7       
 8     private String email;  
 9       
10     public String getUserName() {  
11         return userName;  
12     }  
13     public void setUserName(String userName) {  
14         this.userName = userName;  
15     }  
16     public String getPassword() {  
17         return password;  
18     }  
19     public void setPassword(String password) {  
20         this.password = password;  
21     }  
22     public String getEmail() {  
23         return email;  
24     }  
25     public void setEmail(String email) {  
26         this.email = email;  
27     }     
28       
29     public boolean equals(Object obj){  
30         if(obj == null){  
31             return false;  
32         }  
33         if(obj == this){  
34             return true;  
35         }         
36         if(obj instanceof User){  
37             if(userName.equals(((User) obj).userName) && password.equals(((User) obj).password) && email.equals(((User) obj).email)){  
38                 return true;  
39             }else{  
40                 return false;  
41             }  
42         }else{  
43             return false;  
44         }  
45     }  
46       
47     public String toString(){  
48         StringBuilder sb = new StringBuilder();  
49           
50         sb.append(getClass()).append("[")  
51         .append("userName=").append(userName).append(", ")  
52         .append("password=").append(password).append(", ")  
53         .append("email=").append(email).append("]");  
54           
55         return sb.toString();  
56     }  
57       
58 }  

1)  contentType: 设定提交的数据内容格式, 告诉服务器提交的数据格式

contentType: 不设置情况下默认 “application/x-www-form-urlencoded”格式提交数据。

 

A)  var params={"userName": $("#userName").val(),"password": $("#password").val(),"email" : $("#email").val()};

要提交的对象为javascript对象,$.ajax(url, params, callback, "json"); 在提交之前JQuery自动将javascript对象编码成“application/x-www-form-urlencoded”格式数据。

 

B) var params="userName="+$("#userName").val()+"&password="+$("#password").val()+"&email="+$("#email").val();

提交之前的数据已经按照“application/x-www-form-urlencoded”格式准备完毕,所以在不设定contentType的情况下,服务器端也可以正常解析。

 需要设置contentType的情况:

在寻找ajax提交示例的时候,看到网上有人在提交之前把javascript对象已经用 JSON.stringify(obj)转换为json格式的字符串了。

 1 var params={  
 2                 "userName": $("#userName").val(),  
 3                 "password": $("#password").val(),  
 4                 "email"   : $("#email").val()  
 5                 };  
 6         var url = "<%=webProject%>/register";  
 7         var successFun = function(data, textStatus){  
 8                     alert("success!");  
 9                     alert("responseText="+data.userName);  
10                                     };  
11         var errorFun = function (XMLHttpRequest, textStatus, errorThrown) {  
12             alert("error");  
13                     alert("statusText="+textStatus);  
14                          }  
15         $.ajax({  
16             type: "POST",  
17             url : "<%=webProject%>/register",  
18             data: JSON.stringify(params),  
19             success: successFun,  
20             error: errorFun  
21             //contentType: "application/json",  
22             //dataType: "json"            
23         });  

服务器代码:

 1 /** 
 2  * 处理提交的用户注册信息。 
 3  * @param model 
 4  * @return 
 5  * @throws IOException  
 6  */  
 7 @RequestMapping (method = RequestMethod.POST)  
 8 public void doRegister(@RequestBody User user, HttpServletResponse response) throws IOException{  
 9       
10     System.out.println(user);  
11       
12     String value = "{'userName':'中文', 'password':'123'}";  
13       
14     response.setCharacterEncoding("UTF-8");  
15 /       response.setHeader("content-type", "application/json");  
16       
17     response.getWriter().print(value);  
18     response.getWriter().close();  
19 }  

这个时候发现,不指定contentType情况下,服务器抛出异常:

org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported  

原因很简单,我们准备的数据时string格式的,同时ajax默认提交时告诉服务器数据格式是 "'application/x-www-form-urlencoded",服务器调用相关的Converter解析的时候发现解析不了(因为我们的数 据格式其实是json格式)。

这个时候加上:contentType: "application/json", 问题就解决了。

2、 dataType 的功能和用法:

dataType的功能: 设定HttpHeader中“Accept”域的内容,告诉服务器浏览器可以想要返回的数据格式类型,同时JQuery也会根据该类型对返回的数据进行相应的格式转换。

测试条件: 服务器端采用下面代码直接返回json格式的字符串。

1 String value = "{'userName':'中文', 'password':'123'}";  
2       
3     response.setCharacterEncoding("UTF-8");  
4   
5     response.getWriter().print(value);  
6     response.getWriter().close(); 

dataType 设定为“json”格式时

1 $.ajax({  
2             type: "POST",  
3             url : "<%=webProject%>/register",  
4             data: JSON.stringify(params),  
5             success: successFun,  
6             error: errorFun  
7             //contentType: "application/json",  
8             dataType: "json"              
9         });  

可以正确的打印 alert("userName="+data.userName); data.userName javascript直接访问属性的方式。说明JQuery自动把返回的字符串转化为javascript对象了。

 

dataType 不设定的情况下:

1 $.ajax({  
2             type: "POST",  
3             url : "<%=webProject%>/register",  
4             data: JSON.stringify(params),  
5             success: successFun,  
6             error: errorFun  
7             //contentType: "application/json",  
8             //dataType: "json"            
9         });  

打印出来的 alert("userName="+undefined) 说明JQuery没有对返回的数据进行转换。

 

2、jQuery Ajax 事件

Ajax请求会产生若干不同的事件,我们可以订阅这些事件并在其中处理我们的逻辑。在jQuery这里有两种Ajax事件:局部事件 和 全局事件。

局部事件就是在每次的Ajax请求时在方法内定义的,例如:

1 $.ajax({
2  beforeSend: function(){
3  // Handle the beforeSend event }, complete: function(){
4  // Handle the complete event } // ... });

全局事件是每次的Ajax请求都会触发的,它会向DOM中的所有元素广播,在上面 getScript() 示例中加载的脚本就是全局Ajax事件。全局事件可以如下定义:

1 $("#loading").bind("ajaxSend", function(){
2  $(this).show();
3  }).bind("ajaxComplete", function(){
4  $(this).hide();
5  });

或者:

1  $("#loading").ajaxStart(function(){
2  $(this).show();
3  }); 

我们可以在特定的请求将全局事件禁用,只要设置下 global 选项就可以了:

1 $.ajax({
2  url: "test.html",
3  global: false,// 禁用全局Ajax事件. // ... });

下面是jQuery官方给出的完整的Ajax事件列表:

  • ajaxStart (Global Event)
    This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
    • beforeSend (Local Event)
      This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)
    • ajaxSend (Global Event)
      This global event is also triggered before the request is run.
    • success (Local Event)
      This event is only called if the request was successful (no errors from the server, no errors with the data).
    • ajaxSuccess (Global Event)
      This event is also only called if the request was successful.
    • error (Local Event)
      This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
    • ajaxError (Global Event)
      This global event behaves the same as the local error event.
    • complete (Local Event)
      This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
    • ajaxComplete (Global Event)
      This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.

3. jQuery.get(url, [data], [callback], [type]):使用GET方式来进行异步请求

参数:

url (String) : 发送请求的URL地址.

data (Map) : (可选) 要发送给服务器的数据,以 Key/value 的键值对形式表示。

callback (Function) : (可选) 载入成功时回调函数(只有当Response的返回状态是success才是调用该方法)。

type (String) : (可选)官方的说明是:Type of data to be sent。其实应该为客户端请求的类型(JSON,XML,等等)

 

这是一个简单的 GET 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。示例代码:

1  $.get("./Ajax.aspx", {Action:"get",Name:"lulu"}, function (data, textStatus){
2  //返回的 data 可以是 xmlDoc, jsonObj, html, text, 等等. this; // 在这里this指向的是Ajax请求的选项配置信息,请参考下图 alert(data);
3  //alert(textStatus);//请求状态:success,error等等。
4  当然这里捕捉不到error,因为error的时候根本不会运行该回调函数 //alert(this); });

点击发送请求:

jQuery.get()回调函数里面的 this ,指向的是Ajax请求的选项配置信息:

 

image

 

4. jQuery.post( url, [data], [callback], [type] ) :使用POST方式来进行异步请求

参数:

url (String) : 发送请求的URL地址.

data (Map) : (可选) 要发送给服务器的数据,以 Key/value 的键值对形式表示。

callback (Function) : (可选) 载入成功时回调函数(只有当Response的返回状态是success才是调用该方法)。

type (String) : (可选)官方的说明是:Type of data to be sent。其实应该为客户端请求的类型(JSON,XML,等等)

这是一个简单的 POST 请求功能以取代复杂 $.ajax 。请求成功时可调用回调函数。如果需要在出错时执行函数,请使用 $.ajax。示例代码:

Ajax.aspx:

1 Response.ContentType = "application/json";
2  Response.Write("{result: '" + Request["Name"] + ",你好!(这消息来自服务器)'}");
3 jQuery 代码:
4 $.post("Ajax.aspx", { Action: "post", Name: "lulu" },
5  function (data, textStatus){
6  // data 可以是 xmlDoc, jsonObj, html, text, 等等. //this; // 这个Ajax请求的选项配置信息,请参考jQuery.get()说到的this alert(data.result);
7  }, "json");

点击提交:

这里设置了请求的格式为"json":

image

如果你设置了请求的格式为"json",此时你没有设置Response回来的ContentType 为:Response.ContentType = "application/json"; 那么你将无法捕捉到返回的数据。

注意一下,alert(data.result); 由于设置了Accept报头为“json”,这里返回的data就是一个对象,并不需要用eval()来转换为对象。

posted on 2016-04-02 14:12  jayleke  阅读(10551)  评论(0编辑  收藏  举报
葳蕤工作室