jquery ajax 方法及各参数详解

来源:互联网 发布:淘宝账号被冻结支付宝 编辑:程序博客网 时间:2024/05/04 14:20

在使用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 将自动调用回调函数。(这个我不是很懂)

参数列表:

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

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

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

dataObject,
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

dataTypeString

预期服务器返回的数据类型。设定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 将自动替换 ? 为正确的函数名,以执行回调函数。

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

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

$.ajax({
type: "get",
url: "http://www.cnblogs.com/rss",
beforeSend: function(XMLHttpRequest){
//ShowLoading();},success: function(data, textStatus){
$(".ajax.ajaxResult").html("");
$("item",data).each(function(i, domEle){
$(".ajax.ajaxResult").append("<li>"+$(domEle).children("title").text()+"</li>");
});
},
complete: function(XMLHttpRequest, textStatus){
//HideLoading();},error: function(){
//请求出错处理}});

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

 前段页面: register.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%><%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%><%String webProject = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><base href="<%= basePath %>" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>User Register Page</title><script type="text/javascript" src="<%=webProject%>/resource/js/jquery-1.7.2.min.js"></script><script type="text/javascript" src="<%=webProject%>/resource/js/json2.js"></script><style type="text/css">.error{color: red;}</style><script type="text/javascript">function register(){var params={"userName": $("#userName").val(),"password": $("#password").val(),"email"   : $("#email").val()};var url = "<%=webProject%>/register";var successFun = function(data, textStatus){alert("success!");alert("responseText="+data.userName);alert("statusText="+textStatus);};var errorFun = function (XMLHttpRequest, textStatus, errorThrown) {alert("error");        alert("XMLHttpRequest="+XMLHttpRequest);        alert("statusText="+textStatus);        alert("errorThrown="+errorThrown);         }$.ajax({type: "POST",url : "<%=webProject%>/register",data: JSON.stringify(params),success: successFun,error: errorFun//contentType: "application/json",//dataType: "json"});}</script></head><body><sf:form method="post" modelAttribute="user"><p>用户注册页面:</p><table width="60%" align="center"><colgroup><col width="10%" align="right" /><col /></colgroup><tr><th>用户名:</th><td><sf:input path="userName" /><small>length of userName is not more than 20.</small><br /><sf:errors path="userName" cssClass="error"/></td></tr><tr><th>密码:</th><td><sf:password path="password" /><small>length of password is not less than 6.</small><br /><sf:errors path="password" cssClass="error" /></td></tr><tr><th>邮箱:</th><td><sf:input path="email"/><small>format should confirm to general standard.</small><br /><sf:errors path="email" cssClass="error" /></td></tr><tr><td colspan="2" align="center"><input type="button" value="注册" onclick="register()"/></td></tr></table></sf:form></body></html>

服务器端代码:

package org.study.controller;import java.io.IOException;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.study.domain.User;/** * 用户注册、登陆相关信息的Controller。 * 使用JSON方式处理输入和输出数据。 *  * @author CHEN Dezong * @version 1.0.0 * */@Controller@RequestMapping ("/register")public class RegisterController {/** * 显示用户注册页面。 * @param model * @return */@RequestMapping (method = RequestMethod.GET)public String showRegister(Model model){model.addAttribute(new User());return "register";}/** * 处理提交的用户注册信息。 * @param model * @return * @throws IOException  */@RequestMapping (method = RequestMethod.POST)public void doRegister(HttpServletResponse response) throws IOException{String value = "{'userName':'中文', 'password':'123'}";response.setCharacterEncoding("UTF-8");//response.setHeader("content-type", "application/json");response.getWriter().print(value);response.getWriter().close();}}

POJO 对象 User.java

package org.study.domain;public class User {private String userName;private String password;private String email;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public boolean equals(Object obj){if(obj == null){return false;}if(obj == this){return true;}if(obj instanceof User){if(userName.equals(((User) obj).userName) && password.equals(((User) obj).password) && email.equals(((User) obj).email)){return true;}else{return false;}}else{return false;}}public String toString(){StringBuilder sb = new StringBuilder();sb.append(getClass()).append("[").append("userName=").append(userName).append(", ").append("password=").append(password).append(", ").append("email=").append(email).append("]");return sb.toString();}}


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格式的字符串了。

var params={"userName": $("#userName").val(),"password": $("#password").val(),"email"   : $("#email").val()};var url = "<%=webProject%>/register";var successFun = function(data, textStatus){alert("success!");alert("responseText="+data.userName);};var errorFun = function (XMLHttpRequest, textStatus, errorThrown) {alert("error");              alert("statusText="+textStatus);                 }$.ajax({type: "POST",url : "<%=webProject%>/register",data: JSON.stringify(params),success: successFun,error: errorFun//contentType: "application/json",//dataType: "json"});

服务器代码:

/** * 处理提交的用户注册信息。 * @param model * @return * @throws IOException  */@RequestMapping (method = RequestMethod.POST)public void doRegister(@RequestBody User user, HttpServletResponse response) throws IOException{System.out.println(user);String value = "{'userName':'中文', 'password':'123'}";response.setCharacterEncoding("UTF-8");//response.setHeader("content-type", "application/json");response.getWriter().print(value);response.getWriter().close();}


这个时候发现,不指定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格式的字符串。

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


 

dataType 设定为“json”格式时

 

$.ajax({type: "POST",url : "<%=webProject%>/register",data: JSON.stringify(params),success: successFun,error: errorFun//contentType: "application/json",dataType: "json"});

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

 

dataType 不设定的情况下:

$.ajax({type: "POST",url : "<%=webProject%>/register",data: JSON.stringify(params),success: successFun,error: errorFun//contentType: "application/json",//dataType: "json"});

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

 

2、jQuery Ajax 事件

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

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

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

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

 $("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});

或者:

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

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

 $.ajax({
url: "test.html",
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。示例代码:

     $.get("./Ajax.aspx", {Action:"get",Name:"lulu"}, function (data, textStatus){
    //返回的 data 可以是 xmlDoc, jsonObj, html, text, 等等.this; // 在这里this指向的是Ajax请求的选项配置信息,请参考下图alert(data);
    //alert(textStatus);//请求状态:success,error等等。
    当然这里捕捉不到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:

    Response.ContentType = "application/json";
    Response.Write("{result: '" + Request["Name"] + ",你好!(这消息来自服务器)'}");

    jQuery 代码:

    $.post("Ajax.aspx", { Action: "post", Name: "lulu" },
    function (data, textStatus){
    // data 可以是 xmlDoc, jsonObj, html, text, 等等.//this; // 这个Ajax请求的选项配置信息,请参考jQuery.get()说到的thisalert(data.result);
    }, "json");

    点击提交:

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

    image

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

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

     

     其中很大一部分是第一篇文章作者的贡献,在此对你的辛勤劳动表示感谢。

    参考文献:

    1、http://www.cnblogs.com/yeer/archive/2009/07/23/1529460.html

    2、http://code.jquery.com/jquery-1.7.2.js

  • ajaxStop (Global Event)
    This global event is triggered if there are no more Ajax requests being processed.

    具体的全局事件请参考API文档。

  • 原创粉丝点击