The ajax() method loads remote data through HTTP requests.
This method is the underlying AJAX implementation of jQuery. For simple and easy-to-use high-level implementations, see $.get, $.post, etc. $.ajax() returns the XMLHttpRequest object it created. In most cases you won't need to manipulate this function directly unless you need to manipulate less commonly used options for more flexibility.
In the simplest case, $.ajax() can be used directly without any parameters.
Note: All options can be set globally through the $.ajaxSetup() function.
Grammar
jQuery.ajax([settings])
Parameters | Description | ||||
---|---|---|---|---|---|
settings |
Optional. A collection of key-value pairs used to configure Ajax requests.
The default value of any option can be set through $.ajaxSetup(). <🎜> |
jQuery.get()
使用一个HTTP GET 请求从服务器加载数据。
jQuery.get(url [,data] [,success(data,textStatus,jqXHR)] [dtaType])
url 一个包含发送请求的URL
data 发送给服务器的字符串后键值对
success() 当请求成功时回调的函数
dataType 从服务器返回的预期数据。
用法:
$.get("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
jQuery.getJSON()
使用一个HTTP GET 请求服务器加载JSON 编码的数据。
jQuery.getJSON(url [,data] [,success(data,textStatus,jqXHR)])
url 一个包含发送请求的URL
data 发送给服务器的字符串后键值对
success() 当请求成功时回调的函数
jQuery.getScript()
使用一个HTTP GET请求从服务器加载并执行一个JavaScript文件。
jQuery.getScript(url[success(script,textStatus,jqXHR)])
url 一个包含发送请求的URL
data 发送给服务器的字符串后键值对
用法:
$.getScript("ajax/test.js", function(data, textStatus, jqxhr) { console.log(data); //data returned console.log(textStatus); //success console.log(jqxhr.status); //200 console.log('Load was performed.'); });
jQuery.post([settings])
使用一个HTTP POST请求从服务器加载数据。
jQuery.post(url[,data][,success(data,textStatus,jqXHR)][,dataType])
url 一个包含发送请求的URL
data 发送给服务器的字符串后键值对
success() 当请求成功时回调的函数
用法:
$.post("test.php", { name: "John", time: "2pm" }, function(data) { alert("Data Loaded: " + data); });
.load()
从服务器载入数据并且将返回的HTML代码并插入至匹配的元素中。
.load(url[,data][,complete(responseText,textStatus,XMLHttpRequest)])
url 一个包含发送请求的URL
data 发送给服务器的字符串后键值对
complete 当请求成功时回调的函数
用法:
$('#result').load('ajax/test.html #container');
jQuery.ajax()
执行一个异步的HTTP(ajax)的请求。
参数:
url 类型: Sting 发送请求的地址(默认当前页面)
type 类型:Sting (默认为GET) 请求方式(”POST“或”GET“)
timeout 类型:Number 设置请求超时时间(毫秒),此设置默认覆盖全局。
async 类型:Boolean 默认设置(true)默认设置下所有请求均为一步请求,如果需要同步请求,设置为false。
beforeSend 类型:function 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 对象是唯一的参数。
cache 类型:Boolean 默认为(true) 设置为false 将不会从浏览器缓存中加载请求信息。
complete 类型:Function 请求完成后回调函数,(请求成功或失败时均调用)参数: XMLHttpRequest 对象,成功信息字符串。function ( XMLHttpRequest, textStatus) {this; // the options for this ajax request}
contentType 类型为:String 发送信息至服务器时内容编码类型,默认值适合大多数应用场合。
data 类型:Object String 发送到服务器的数据。将自动转换为请求字符串格式,GET请求附加在URL后
dataType 类型:String 预期服务器返回的数据类型, ”xml“返回XML文档。”html“返回纯文本信息,包含script 元素。”script“返回纯文本JavaScript 代码,不会自动缓存 结果。”json“返回JSON 数组。”jsonp“JSONP格式。
error 类型:function 请求失败时将调用此方法。
global 类型:Boolean 是否触发全局AJAX事件。默认为(true) 设置为false 将不会触发全局ajax 事件,可用于控制不同的AJAX事件。
ifModified 类型:Boolean 默认为false 仅在服务器数据改变时获取新数据。
processData 类型:Boolean 默认为(true)默认情况下,发送的数据发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 "application/x-www-form- urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
success 类型:Function 请求成功后回调函数。这个方法有两个参数:服务器返回数据,返回状态。
$(document).ready(function() { jQuery("#clearCac").click(function() { jQuery.ajax({ url: "/Handle/Do.aspx", type: "post", data: { id: '0' }, dataType: "json", success: function(msg) { alert(msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); }, complete: function(XMLHttpRequest, textStatus) { this; // 调用本次AJAX请求时传递的options参数 } }); }); });
The first parameter XMLHttpRequest returned by the error event has some useful information:
XMLHttpRequest.readyState:
Status code
0 - (Uninitialized) The send() method has not been called yet
1 - (Loading) The send() method has been called and the request is being sent
2 - (Loading completed) The send() method has been executed and all response content has been received
3 - (Interactive) Parsing response content
4 - (Complete) The response content parsing is completed and can be called on the client
XMLHttpRequest.status:
1xx-Information prompt
These status codes indicate provisional responses. The client should be prepared to receive one or more 1xx responses before receiving a regular response.
100-continue.
101-Switch protocol.
2xx-Success
This type of status code indicates that the server successfully accepted the client request.
200-OK. The client request was successful.
201-Created.
202-Accepted.
203-Non-authoritative information.
204-No content.
205-Reset content.
206-Part of the content.
3xx-Redirect
The client browser must take additional actions to fulfill the request. For example, the browser may have to request a different page on the server, or repeat the request through a proxy server.
301 - The object has been permanently moved, i.e. permanently redirected.
302 - The object has been temporarily moved.
304-Not modified.
307 - Temporary redirect.
4xx-Client Error
An error occurred and there seems to be a problem with the client. For example, the client requests a page that does not exist, and the client does not provide valid authentication information. 400 - Bad request.
401 - Access Denied. IIS defines many different 401 errors, which indicate more specific error causes. These specific error codes show up in the browser, but not in the IIS logs:
401.1 - Login failed.
401.2 - Server configuration caused login failure.
401.3 - Not authorized due to ACL restriction on resource.
401.4 - Filter authorization failed.
401.5-ISAPI/CGI application authorization failed.
401.7 – Access is denied by the URL authorization policy on the web server. This error code is specific to IIS6.0.
403 - Forbidden: IIS defines a number of different 403 errors, which indicate more specific causes of the error:
403.1 - Execution access prohibited.
403.2 - Read access forbidden.
403.3 - Write access prohibited.
403.4 - SSL required.
403.5 - SSL128 required.
403.6 - IP address rejected.
403.7 - Client certificate required.
403.8 - Site access denied.
403.9-Too many users.
403.10 - Invalid configuration.
403.11-Password change.
403.12 - Access to mapping table denied.
403.13 - Client certificate revoked.
403.14 - Directory listing denied.
403.15 - Client access permission exceeded.
403.16 - Client certificate is not trusted or invalid.
403.17 - The client certificate has expired or is not yet valid.
403.18 - The requested URL cannot be executed in the current application pool. This error code is specific to IIS6.0.
403.19 - CGI cannot be executed for clients in this application pool. This error code is specific to IIS6.0.
403.20-Passport login failed. This error code is specific to IIS6.0.
404-Not Found.
404.0-(None) – File or directory not found.
404.1 - The web site cannot be accessed on the requested port.
404.2 - This request is blocked by the Web Services extension locking policy.
404.3-MIME mapping policy blocks this request.
405-The HTTP verb used to access this page is not allowed (method not allowed)
406 - The client browser does not accept the MIME type of the requested page.
407 - Proxy authentication required.
412 - Precondition failed.
413 – The request entity is too large.
414 - Request URI too long.
415 – Unsupported media type.
416 – The requested range cannot be satisfied.
417 – Execution failed.
423 – Locked error.
5xx-Server Error
The server was unable to complete the request because it encountered an error.
500 - Internal server error.
500.12 - The application is busy restarting on the web server.
500.13 - The web server is too busy.
500.15 - Direct request to Global.asa is not allowed.
500.16 – Incorrect UNC authorization credentials. This error code is specific to IIS6.0.
500.18 – The URL authorization store cannot be opened. This error code is specific to IIS6.0.
500.100 - Internal ASP error.
501 - Header value specifies an unimplemented configuration.
502 - The web server received an invalid response while acting as a gateway or proxy server.
502.1-CGI application timed out.
502.2-CGI application error. application.
503-Service unavailable. This error code is specific to IIS6.0.
504-Gateway timeout.
505 - HTTP version is not supported.
jQuery.param()
Creates an array, a plain object, or a serialized representation of a jQuery object for use with URL query strings or Ajax requests.
jQuery.param(obj)
obj An array for serialization, a normal object, or a jQuery object.
jQuery.param( obj, traditional )
obj An array for serialization, a normal object, or a jQuery object.
traditional
A Boolean value indicating whether traditional "shallow" serialization is performed.
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
$.param({ a: { b:1,c:2 }, d: [3,4,{ e:5 }] }) // "a[b]=1&a[c]=2&d[]=3&d []=4&d[2][e]=5"