7. Ajax
7.1 $.ajax(properties)
使用HTTP请求(XMLHttpRequest)载入一个远程页面。
这是jQuery的低级AJAX实现。要查看高级抽象,见$.set、$.post等。
$.ajax()返回创建好的XMLHttpRequest对象。多数情况下并不需要直接操纵这个对象, 但是如果需要手动中止请求,它也是可用的
。
注意:要确保服务器返回正确的MIME类型(例如:XML是“text/xml”)。如果返回了错误的MIME类型就会导致jQuery无法处理的严
重问题。
支持的数据类型包括(见dataType选项):
"xml": 返回一个可以由jQuery对象处理的XML文档。
"html": 返回纯文本格式的HTML,包括求值后的脚本标记。
"script": 将响应作为Javascript语句求值,并返回纯文本。
"json": 将响应作为JSON求值,并返回一个Javascript对象。
$.ajax()带有一个参数--“名/值对”形式的一个对象,用于初始化和处理请求。 以下就是可用的所有“名/值对”:
(String) url - 要将请求发送到的URL地址。
(String) type - 请求的类型 ("POST" 或 "GET"), 默认是 "GET"。
(String) dataType - 期望从服务器端返回的数据类型。 无默认值:如果服务器返回XML,就将responseXML传递到回调函数,否则
将resposeText传递到回调函数。
(Boolean) ifModified - 只有响应自上次请求后被修改过才承认是成功的请求。 是通过检查头部的Last-Modified值实现的。默认
值为false,即忽略 对部分的检查
(Number) timeout - 覆盖全局延迟的局部延迟,例如,在其他所有延迟经过1秒钟后,启动一个较长延迟的单独请求。 有关全局延
迟,见$.ajaxTimeout()。
(Boolean) global - 是否为当前的请求触发全局AJAX事件处理函数,默认值为true。 设置为false可以防止触发像ajaxStart或
ajaxStop这样的全局事件处理函数。
(Function) error - 当请求失败时调用的函数。 这个函数会得到三个参数:XMLHttpRequest对象、一个描述所发生的错误类型的
字符串和一个可选异常对象(如果有)。
(Function) success - 当请求成功时调用的函数。 这个函数会得到一个参数:从服务器返回的数据(根据“dataType”进行了格
式化)。
(Function) complete - 当请求完成时调用的函数。 这个函数会得到两个参数:XMLHttpRequest对象和一个描述请求成功的类型的
字符串。
(Object|String) data - 要发送到服务器的数据。如果还不是一个字符串,就自动轮换为一个查询字符串。 即附加到GET请求的
url后面的字符串。要防止自动处理见processData选项。
(String) contentType - 设置发送请求的content=type。 默认值是 "application/x-www-form-urlencoded", 这个值能满足多数
情况。
(Boolean) processData - 在默认的情况下,如果data选项传进的数据是一个对象而不是字符串,将会自动地被处理和转换成一个
查询字符串, 以适应默认的content-type--"application/x-www-form-urlencoded"。如果想发送DOMDocuments,就要把这个选
项设置为false。
(Boolean) async - 在默认的情况下,所有请求都是以异步的方式发送的(值为true)。 如果要使用同步方式,需要将此项设置为
false。
(Function) beforeSend - 用于设置自定义头部等信息的预调用函数,接收一个唯一的参数--XMLHttpRequest对象。
Load a remote page using an HTTP request.
This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions.
$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate
directly, but it is available if you need to abort the request manually.
Note: Make sure the server sends the right mimetype (eg. xml as "text/xml"). Sending the wrong mimetype will get
you into serious trouble that jQuery can't solve.
Supported datatypes are (see dataType option):
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text, included script tags are evaluated.
"script": Evaluates the response as Javascript and returns it as plain text.
"json": Evaluates the response as JSON and returns a Javascript Object
$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These
are all the key/values that can be used:
(String) url - The URL to request.
(String) type - The type of request to make ("POST" or "GET"), default is "GET".
(String) dataType - The type of data that you're expecting back from the server. No default: If the server sends
xml, the responseXML, otherwise the responseText is passed to the success callback.
(Boolean) ifModified - 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.
(Number) timeout - Local timeout to override global timeout, eg. to give a single request a longer timeout while
all others timeout after 1 second. See $.ajaxTimeout() for global timeouts.
(Boolean) global - Whether to trigger global AJAX event handlers for this request, default is true. Set to false to
prevent that global handlers like ajaxStart or ajaxStop are triggered.
(Function) error - A function to be called if the request fails. The function gets passed tree arguments: The
XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one
occured.
(Function) success - A function to be called if the request succeeds. The function gets passed one argument: The
data returned from the server, formatted according to the 'dataType' parameter.
(Function) complete - A function to be called when the request finishes. The function gets passed two arguments:
The XMLHttpRequest object and a string describing the type of success of the request.
(Object|String) data - Data to be sent to the server. Converted to a query string, if not already a string. Is
appended to the url for GET-requests. See processData option to prevent this automatic processing.
(String) contentType - When sending data to the server, use this content-type. Default is "application/x-www-form-
urlencoded", which is fine for most cases.
(Boolean) processData - By default, data passed in to the data option as an object other as 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 DOMDocuments, set this option to false.
(Boolean) async - By default, all requests are send asynchronous (set to true). If you need synchronous requests,
set this option to false.
(Function) beforeSend - A pre-callback to set custom headers etc., the XMLHttpRequest is passed as the only
argument.
返回值
XMLHttpRequest
参数
properties (Map): Key/value pairs to initialize the request with.
示例
说明:
载入并执行一个JavaScript文件。
jQuery 代码:
$.ajax({ type: "GET", url: "test.js", dataType: "script" })
说明:
将数据保存到服务器,并在保存完成后通报用户。
jQuery 代码:
$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data
Saved: " + msg ); } });
说明:
同步载入数据。当请求处于活动期间阻塞浏览器。 如果必须同步载入数据,最好是通过其他手段来阻止用户的交互,而不是阻塞整
个浏览器。
jQuery 代码:
var html = $.ajax({ url: "some.php", async: false }).responseText;
说明:
将一个XML文档作为数据发送到服务器。 通过将processData选项设置为false,可以避免把自动把数据转换为字符串。
jQuery 代码:
var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success:
handleResponse });
7.2 $.ajaxSetup(settings)
Setup global settings for AJAX requests.
See $.ajax for a description of all available options.
返回值
undefined
参数
settings (Map): Key/value pairs to use for all AJAX requests
示例
说明:
Sets the defaults for AJAX requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET.
The following AJAX requests then sends some data without having to set anything else.
jQuery 代码:
$.ajaxSetup( { url: "/xmlhttp/", global: false, type: "POST" } ); $.ajax({ data: myData });
7.3
$.ajaxTimeout(time)
Set the timeout of all AJAX requests to a specific amount of time. This will make all future AJAX requests timeout
after a specified amount of time.
Set to null or 0 to disable timeouts (default).
You can manually abort requests with the XMLHttpRequest's (returned by all ajax functions) abort() method.
Deprecated. Use $.ajaxSetup instead.
返回值
undefined
参数
time (Number): How long before an AJAX request times out.
示例
说明:
Make all AJAX requests timeout after 5 seconds.
jQuery 代码:
$.ajaxTimeout( 5000 );
7.4 $.get(url, params, callback)
Load a remote page using an HTTP GET request.
返回值
XMLHttpRequest
参数
url (String): The URL of the page to load.
params (Map): (optional) Key/value pairs that will be sent to the server.
callback (Function): (optional) A function to be executed whenever the data is loaded.
示例
jQuery 代码:
$.get("test.cgi");
jQuery 代码:
$.get("test.cgi", { name: "John", time: "2pm" } );
jQuery 代码:
$.get("test.cgi", function(data){ alert("Data Loaded: " + data); });
jQuery 代码:
$.get("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); } );
7.5 $.getIfModified(url, params, callback)
Load a remote page using an HTTP GET request, only if it hasn't been modified since it was last retrieved.
返回值
XMLHttpRequest
参数
url (String): The URL of the page to load.
params (Map): (optional) Key/value pairs that will be sent to the server.
callback (Function): (optional) A function to be executed whenever the data is loaded.
示例
jQuery 代码:
$.getIfModified("test.html");
jQuery 代码:
$.getIfModified("test.html", { name: "John", time: "2pm" } );
jQuery 代码:
$.getIfModified("test.cgi", function(data){ alert("Data Loaded: " + data); });
jQuery 代码:
$.getifModified("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); } );
7.6 $.getJSON(url, params, callback)
Load JSON data using an HTTP GET request.
返回值
XMLHttpRequest
参数
url (String): The URL of the page to load.
params (Map): (optional) Key/value pairs that will be sent to the server.
callback (Function): A function to be executed whenever the data is loaded.
示例
jQuery 代码:
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });
jQuery 代码:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); } );
7.7 $.getScript(url, callback)
Loads, and executes, a remote JavaScript file using an HTTP GET request.
Warning: Safari <= 2.0.x is unable to evalulate scripts in a global context synchronously. If you load functions
via getScript, make sure to call them after a delay.
返回值
XMLHttpRequest
参数
url (String): The URL of the page to load.
callback (Function): (optional) A function to be executed whenever the data is loaded.
示例
jQuery 代码:
$.getScript("test.js");
jQuery 代码:
$.getScript("test.js", function(){ alert("Script loaded and executed."); });
7.8 $.post(url, params, callback)
Load a remote page using an HTTP POST request.
返回值
XMLHttpRequest
参数
url (String): The URL of the page to load.
params (Map): (optional) Key/value pairs that will be sent to the server.
callback (Function): (optional) A function to be executed whenever the data is loaded.
示例
jQuery 代码:
$.post("test.cgi");
jQuery 代码:
$.post("test.cgi", { name: "John", time: "2pm" } );
jQuery 代码:
$.post("test.cgi", function(data){ alert("Data Loaded: " + data); });
jQuery 代码:
$.post("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); } );
7.9 ajaxComplete(callback)
Attach a function to be executed whenever an AJAX request completes.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.
返回值
jQuery
参数
callback (Function): The function to execute.
示例
说明:
Show a message when an AJAX request completes.
jQuery 代码:
$("#msg").ajaxComplete(function(request, settings){ $(this).append("<li>Request Complete.</li>"); });
7.10 ajaxError(callback)
Attach a function to be executed whenever an AJAX request fails.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback. A third argument, an
exception object, is passed if an exception occured while processing the request.
返回值
jQuery
参数
callback (Function): The function to execute.
示例
说明:
Show a message when an AJAX request fails.
jQuery 代码:
$("#msg").ajaxError(function(request, settings){ $(this).append("<li>Error requesting page " + settings.url +
"</li>"); });
7.11 ajaxSend(callback)
Attach a function to be executed before an AJAX request is send.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.
返回值
jQuery
参数
callback (Function): The function to execute.
示例
说明:
Show a message before an AJAX request is send.
jQuery 代码:
$("#msg").ajaxSend(function(request, settings){ $(this).append("<li>Starting request at " + settings.url +
"</li>"); });
7.12 ajaxStart(callback)
Attach a function to be executed whenever an AJAX request begins and there is none already active.
返回值
jQuery
参数
callback (Function): The function to execute.
示例
说明:
Show a loading message whenever an AJAX request starts (and none is already active).
jQuery 代码:
$("#loading").ajaxStart(function(){ $(this).show(); });
7.13 ajaxStop(callback)
Attach a function to be executed whenever all AJAX requests have ended.
返回值
jQuery
参数
callback (Function): The function to execute.
示例
说明:
Hide a loading message after all the AJAX requests have stopped.
jQuery 代码:
$("#loading").ajaxStop(function(){ $(this).hide(); });
7.14 ajaxSuccess(callback)
Attach a function to be executed whenever an AJAX request completes successfully.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.
返回值
jQuery
参数
callback (Function): The function to execute.
示例
说明:
Show a message when an AJAX request completes successfully.
jQuery 代码:
$("#msg").ajaxSuccess(function(request, settings){ $(this).append("<li>Successful Request!</li>"); });
7.15 load(url, params, callback)
Load HTML from a remote file and inject it into the DOM.
Note: Avoid to use this to load scripts, instead use $.getScript. IE strips script tags when there aren't any other
characters in front of it.
返回值
jQuery
参数
url (String): The URL of the HTML file to load.
params (Object): (optional) A set of key/value pairs that will be sent as data to the server.
callback (Function): (optional) A function to be executed whenever the data is loaded (parameters: responseText,
status and response itself).
示例
HTML 代码:
<div id="feeds"></div>
jQuery 代码:
$("#feeds").load("feeds.html");
结果:
<div id="feeds"><b>45</b> feeds found.</div>
说明:
Same as above, but with an additional parameter and a callback that is executed when the data was loaded.
jQuery 代码:
$("#feeds").load("feeds.html", {limit: 25}, function() { alert("The last 25 entries in the feed have been loaded");
} );
7.16 loadIfModified(url, params, callback)
Load HTML from a remote file and inject it into the DOM, only if it's been modified by the server.
返回值
jQuery
参数
url (String): The URL of the HTML file to load.
params (Map): (optional) Key/value pairs that will be sent to the server.
callback (Function): (optional) A function to be executed whenever the data is loaded (parameters: responseText,
status and response itself).
示例
HTML 代码:
<div id="feeds"></div>
jQuery 代码:
$("#feeds").loadIfModified("feeds.html");
结果:
<div id="feeds"><b>45</b> feeds found.</div>
7.17 serialize()
Serializes a set of input elements into a string of data. This will serialize all given elements.
A serialization similar to the form submit of a browser is provided by the form plugin. It also takes multiple-
selects into account, while this method recognizes only a single option.
返回值
String
示例
说明:
Serialize a selection of input elements to a string
HTML 代码:
<input type='text' name='name' value='John'/> <input type='text' name='location' value='Boston'/>
jQuery 代码:
$("input[@type=text]").serialize();


No comments:
Post a Comment