jQuery.ajax() 的参数 settings

创建时间:
2014-09-08 00:56
最近更新:
2018-09-12 12:08

Official Documentation of settings

Type: PlainObject
A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().

-- http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings - 此处列出了 settings 参数的全部有效属性。可通过 $.ajaxSetup() 设置该参数的默认值。

测试记录 - $.ajax()settings 参数中可添加任意数量的自定义属性

//添加自定义参数 Btn:
$.ajax({ url : "test1.html", type : "get", Btn : "按钮一" });
$.ajax({ url : "test2.html", type : "get", Btn : "按钮二" });
$.ajax({ url : "test3.html", type : "get", Btn : "按钮三" });

//处理参数:
JqueryObject
    .beforeSend(function(e, xhr, o){
        //操作o.Btn
    })
    .ajaxSuccess(function(e, xhr, o){
        //操作o.Btn
    })
    .ajaxError(function(e, xhr, o){
        //操作o.Btn
    });

jQuery.ajax([settings]) 中的 settings 的全部 key

  1. accepts (default: depends on dataType)
  2. async (default: true)
  3. beforeSend
  4. cache (default: true, false for dataType 'script' and 'jsonp')
  5. complete
  6. contents
  7. contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
  8. context
  9. converters (default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML})
  10. crossDomain (default: false for same-domain requests, true for cross-domain requests)
  11. data
  12. dataFilter
  13. dataType (default: Intelligent Guess (xml, json, script, or html))
  14. error
  15. global (default: true)
  16. headers (default: {})
  17. ifModified (default: false)
  18. isLocal (default: depends on current location protocol)
  19. jsonp
  20. jsonpCallback
  21. method (default: 'GET')
  22. mimeType
  23. password
  24. processData (default: true)
  25. scriptCharset
  26. statusCode (default: {})
  27. success
  28. timeout
  29. traditional
  30. type (default: 'GET')
  31. url (default: The current page)
  32. username
  33. xhr (default: ActiveXObject when available (IE), the XMLHttpRequest otherwise)
  34. xhrFields

-- From http://api.jquery.com/jQuery.ajax/

测试记录 - dataType

测试一: 无 dataType 时 收到的是 字符串

$.ajax({
    url: url,
    type: 'post',
    data: data,
    success: function(data) {
        //以下两行均输出 true:
        console.log(data === 'true');
        console.log(typeof(data) === 'string');
    }
});

测试二: 有 dataType 时 收到的是 JSON

$.ajax({
    url: url,
    type: 'post',
    data: data,
    dataType: 'json',
    success: function(data) {
        //以下两行均输出 true:
        console.log(data === true);
        console.log(typeof(data) === 'boolean');
    }
});

上述两组测试均请求以下控制器

public ActionResult Delete(ulong id)
{
    ...
    return Json(true);
}

以下是这些 key 的备忘

accepts

Map
Default: depends on DataType
The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method.

async

Boolean
Default: true
默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

beforeSend(jqXHR,settings)

Function
发送请求前可修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。这是一个Ajax事件。如果返回false可以取消本次ajax请求。
Tony尚未证实:在此回调函数中,this指向调用本次AJAX请求时传递的options参数——《jQuery中文手册》
A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings maps are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

cache

Boolean
默认为true,但dataType为script或jsonp时默认为false。设置为false将不缓存此页面。
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser. Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.

complete(jqXHR,textStatus)

Function, Array
请求完成后将回调此函数(请求成功或失败之后均调用)。参数:jqXHR对象和一个描述成功请求类型的字符串。Ajax事件。
Tony尚未证实:在此回调函数中,this指向调用本次AJAX请求时传递的options参数——《jQuery中文手册》
A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

contents

(added 1.5)
Map
A map of string/regular-expression pairs that determine how jQuery will parse the response, given its content type.
制定jQuery如何解析响应的规则。

contentType

String
Default: 'application/x-www-form-urlencoded'
发送信息至服务器时内容编码类型。默认值适合大多数情况。如果你明确地传递了一个content-type给$.ajax()那么他必定会发送给服务器(即使没有数据要发送)
When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. If you explicitly pass in a content-type to $.ajax() then it'll always be sent to the server (even if no data is sent). Data will always be transmitted to the server using UTF-8 charset; you must decode this appropriately on the server side.

context

Object
这个对象用于设置Ajax相关回调函数的上下文。也就是说,让回调函数内this指向这个对象(如果不设定这个参数,那么this就指向调用本次AJAX请求时传递的options参数)。比如指定一个DOM元素作为context参数,这样就设置了success回调函数的上下文为这个DOM元素。
This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). For example specifying a DOM element as the context will make that the context for the complete callback of a request, like so:

$.ajax({
    url:"test.html",
    context:document.body,
    success:function(){
        $(this).addClass("done");
    }
});

converters

(added 1.5)
Map
Default: {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML}
A map of dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response

crossDomain

(added 1.5)
Boolean
Default: false for same-domain requests, true for cross-domain requests
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another
domain.

data

Object, String
发送到服务器的数据。将自动转换为请求字符串格式。GET请求中将附加在URL后。查看processData选项说明以禁止此自动转换。必须为Key/Value格式。如果为数组,jQuery将自动为不同值对应同一个名称。如{foo:["bar1","bar2"]}转换为'&foo=bar1&foo=bar2'。
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

dataFilter(data,type)

Function
给Ajax返回的原始数据的进行预处理的函数。提供data和type两个参数:data是Ajax返回的原始数据,type是调用jQuery.ajax时提供的dataType参数。函数返回的值将由jQuery进一步处理。

function(data,type){
    //对Ajax返回的原始数据进行预处理
    return data//返回处理后的数据
}

A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.

Tony测试记录:
dataFilter返回的值,将传递至success(data,textStatus,jqXHR)的data,而不会改变jqXHR。
dataFilter如不返回值,success(data,textStatus,jqXHR)中的data将为""。
dataFilter不能改变jQuery的流程(不能决定由success还是error来做后续的处理)。

dataType

可能的值

String
Default: Intelligent Guess (xml, json, script, or html)
预期服务器返回的数据类型。如果不指定,jQuery将自动根据HTTP包MIME信息来智能判断,比如XML MIME类型就被识别为XML。在1.4中,JSON就会生成一个JavaScript对象,而script则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

"xml":
返回XML文档,可用jQuery处理。
Returns a XML document that can be processed via jQuery.

"html":
返回纯文本HTML信息;包含的script标签会在插入dom时执行。
Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script":
返回纯文本JavaScript代码。不会自动缓存结果。除非设置了"cache"参数。'''注意:'''在远程请求时(不在同一个域下),所有POST请求都将转为GET请求。(因为将使用DOM的script标签来加载)
Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.

"json":
返回JSON数据。
Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

"jsonp":
JSONP格式。使用JSONP形式调用函数时,如"myurl?callback=?"jQuery将自动替换?为正确的函数名,以执行回调函数。
Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

"text":
返回纯文本字符串
A plain text string.

multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

关于dataType的跨浏览器测试

使用下述代码向服务器发出请求:
$.ajax({
    //dataType:"text",
    success:function(data){
        alert(data);
        alert(data==="");
    }
});

当服务器返回string.Empty时,
TT4.8(1000)/IE9.0.8112.16421/CM23.0.1271.97m均接收到string.Empty并弹窗显示true;
而FF18.0弹窗显示“[object XMLDocument]”与false。

上述测试代码中是否有dataType:"text",在IE9.0.8112.16421/CM23.0.1271.97m/FF18.0中唯一的区别是:
有则请求头中:Accept:text/plain, */*; q=0.01
无则请求头中:Accept:*/*
Tony结论:非常明显,无则让客户端根据响应去猜,结果IE与CM都猜对了,只有FF猜错了。

解决方案:
取消对dataType:"text"的注释即可。
因此从2013-01-14开始Tony将dataType:"text"加入默认的$.ajaxSetup({})设置中。

Tony测试记录

2013-06-15 在 IE9.0.8112.16421 中测试:
当dataType为""时, 请求标头中为“Accept */*”;
当dataType为"text"时,请求标头中为“Accept text/plain, */*; q=0.01”;
当dataType为"json"时,请求标头中为“Accept application/json, text/javascript, */*; q=0.01”。

测试发现:
$.ajax({dataType:""})

$.ajax({dataType:"json"})
能够覆盖
$.ajaxSetup({dataType:"text"})。

error(jqXHR,textStatus,errorThrown)

Function
(默认:自动判断(xml或html))请求失败时调用此函数。有以下三个参数:XMLHttpRequest对象、错误信息、(可选)捕获的异常对象。如果发生了错误,错误信息(第二个参数)除了得到null之外,还可能是"timeout","error","notmodified"和"parsererror"。Ajax事件。

function(jqXHR,textStatus,errorThrown){
    //通常textStatus和errorThrown之中只有一个会包含信息
    //Tony尚未证实:在此回调函数中,this指向调用本次AJAX请求时传递的options参数——《jQuery中文手册》
}

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

global

Boolean
Default: true
是否触发全局AJAX事件。设置为false将不会触发全局AJAX事件,如ajaxStart或ajaxStop可用于控制不同的Ajax事件。
Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.

headers

(added 1.5)
Map
Default: {}
A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.

2012-04-24 Tony计划今后使用jQuery时,统一预先设置$.ajaxSetup({headers:{IsAjaxRequest:true}}),便于在C#中区分请求源。类似于C#中的IsCallback、IsPostBack。经测试GET/POST均可,但GET时必须设置$.ajaxSetup({cache:false})避免浏览器缓存。

有网友使用下述代码实现同一目的:

//用$.ajax()可在发送AJAX请求之前创建自定义header头信息:
$.ajax({
    type:"GET",
    url:"Test.htm",
    beforeSend:function(XMLHttpRequest){
        XMLHttpRequest.setRequestHeader("RequestType", "AJAX");
    },
    success:function(){}
});

此网友说,如使用原生AJAX而非jQuery等库包装的AJAX,同样可使用XMLHttpRequest.setRequestHeader()创建自定义header头信息。

使用jQuery的$.ajax() / $.get() / $.post()方法时,会向服务器传递值为XMLHttpRequest的头信息X-Requested-With。
同时jQuery的AJAX会向服务器传递Request.ServerVariables["REQUEST_METHOD"],其值为GET或POST。

ifModified

Boolean
Default: false
仅在服务器数据改变时获取新数据。使用HTTP包Last-Modified头信息判断。在jQuery1.4中,他也会检查服务器指定的'etag'来确定数据没有被修改过。
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.
In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.

isLocal

(added 1.5.1)
Boolean
Default: depends on current location protocol
Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method.

jsonp

String
在一个jsonp请求中重写回调函数的名字。这个值用来替代在"callback=?"这种GET或POST请求中URL参数里的"callback"部分,比如{jsonp:'onJsonPLoad'}会导致将"onJsonPLoad=?"传给服务器。
Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?"
for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }

jsonpCallback

String, Function
为jsonp请求指定一个回调函数名。这个值将用来取代jQuery自动生成的随机函数名。这主要用来让jQuery生成度独特的函数名,这样管理请求更容易,也能方便地提供回调函数和错误处理。你也可以在想让浏览器缓存GET请求的时候,指定这个回调函数名。
Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser
caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

method

mimeType

(added 1.5.1)
String
A mime type to override the XHR mime type.

password

String
用于响应HTTP访问认证请求的密码
A password to be used in response to an HTTP access authentication request.

processData

Boolean
Default: true
默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型"application/x-www-form-urlencoded"。如果要发送DOM树信息或其它不希望转换的信息,请设置为false。
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

scriptCharset

String
只有当请求时dataType为"jsonp"或"script",并且type是"GET"才会用于强制修改charset。通常只在本地和远程的内容编码不同时使用。
Only for requests with "jsonp" or "script" dataType and "GET" type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.

statusCode

(added 1.5)
Map
Default: {}
A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

$.ajax({
    statusCode:{
        404:function(){alert('pagenotfound');}
    }
});

If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.

success(data,textStatus,jqXHR)

Function, Array
请求成功后的回调函数。Ajax事件。

function(data,textStatus,jqXHR){
    //data:由服务器返回,并根据dataType参数进行处理后的数据,可能是xmlDoc,jsonObj,html,text,等等。
    //Tony已证实:在此回调函数中,this指向调用本次AJAX请求时传递的options参数——《jQuery中文手册》
}

A function to be called if the request succeeds.
The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter;
a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object.
As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.

TonyRemark:
jQuery源码中将status>=200 && status<300 || status===304归为success,否则归为error。

timeout

Number
设置请求超时时间(毫秒)。此设置将覆盖全局设置。
Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object
will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

traditional

Boolean
如果你想要用传统的方式来序列化数据,那么就设置为true。
Set this to true if you wish to use the traditional style of param serialization.

type

String
Default: 'GET'
请求方式("POST"或"GET")。注意:其它HTTP请求方法,如PUT和DELETE也可以使用,但仅部分浏览器支持。
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

url

String
发送请求的地址。
Default: The current page 当前页地址
A string containing the URL to which the request is sent.

username

String
用于响应HTTP访问认证请求的用户名
A username to be used in response to an HTTP access authentication request.

xhr

Function
Default: ActiveXObject when available (IE), the XMLHttpRequest otherwise
需要返回一个XMLHttpRequest对象。默认在IE下是ActiveXObject而其他情况下是XMLHttpRequest。用于重写或者提供一个增强的XMLHttpRequest对象。这个参数在jQuery1.3以前不可用。
Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.

xhrFields

(added 1.5.1)
Map
A map of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed.

$.ajax({
    url:a_cross_domain_url,
    xhrFields:{withCredentials:true}
});

In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.