Manual:Ajax/zh

Ajax is a term for using JavaScript to load parts of a page on demand. To use Ajax in MediaWiki, it is recommended that your JavaScript code uses, or the mediawiki.api JavaScript module. Typically, you would perform a MediaWiki API query over Ajax.

Before MW 1.38, MediaWiki used to offer a deprecated Ajax interface for use by extensions. See. However, use of Sajax is discouraged since MediaWiki 1.16, the first release of MediaWiki to ship.

Asynchronous requests
An asynchronous request sends some data to the server, and continues execution. Some time later, the server might return a response (depending on the type of request); in which case the response will be passed to a JavaScript function for handling. Another function may be supplied to handle the case that the request fails for some reason. Below is an example call to the login API by posting the username and password.

Alternatively, you can use jQuery's functions directly:

The function "mw.util.wikiScript" is available since 1.18 onwards.

Synchronous request
The other kind of request sends some data to the server, and waits for the response. This means that the JavaScript will be blocked until the server returns some data, or the request fails for some reason. The following example retrieves the "What links here" list of a template:

( is a JavaScript standard function that returns an object from its string representation in JSON format.)

限制
Due to the same origin policy, it is difficult for a script on an external site to retrieve data from a wiki that is hosted on a different domain &mdash; for example, one cannot directly retrieve data from  to. Newer browsers support an explicit instruction to permit this access via cross-origin resource sharing but this will only work with servers that are configured to issue the appropriate headers, and the user must be using a recent browser that recognises it. Developers with concerns about legacy browsers can't rely on CORS yet.

It is possible to circumvent the Same-Origin policy using JSONP instead of plain JSON which will work in older browsers (including Internet Explorer 6).

Related deprecated functionality
Sajax is an ancient Ajax library that (as of September 2012) is still part of core code and is used by some extensions. 別使用它請用 來取代. Some extensions, whether using Sajax or not, make Ajax calls through the obsolete AjaxDispatcher (see ) by invoking. They should instead make MediaWiki requests to API modules.



參見

 * - Extensions that use the Ajax interface of MediaWiki.



外部連結

 * (JavaScript module)
 * jQuery.ajax (jQuery method)

General information on XMLHttpRequest:
 * XMLHttpRequest specification at W3.org
 * XMLHttpRequest on Wikipedia
 * XMLHttpRequest on MDN