This page is a translated version of the page Manual:Ajax and the translation is 27% complete.
Other languages:

O MediaWiki oferece uma interface (depreciada) de Ajax para ser usada por extensões. Ajax é um termo usado para quando o JavaScript carrega partes da página sob demanda. MediaWiki 1.16 shipped jQuery , accordingly use of Sajax is discouraged.

Portanto, o código JavaScript deve usar como alternativa o jQuery.ajax() (ou o módulo mediawiki.api). Realiza-se uma consulta à API do MediaWiki pelo Ajax (em vez de action=ajax ).


Solicitações assíncronas

Uma solicitação assíncrona envia alguns dados ao servidor, e continua a execução. Depois de um tempo, o servidor poderá retornar uma resposta (dependendo do tipo da solicitação). Nesse caso, a resposta seria lidada por uma função JavaScript. Outra função pode ser fornecida para lidar com o caso da solicitação falhar por alguma razão. Abaixo está uma chamada de exemplo à API de autenticação usando um nome de usuário e uma senha.

mw.loader.using( 'mediawiki.api', function () {
	( new mw.Api() ).get( {
		action: 'query',
		lgname: 'foo',
		lgpassword: 'foobar'
	} ).done( function ( data ) {
		alert( data );
	} );
} );

Alternatively, you can use jQuery's functions directly:

        // request type ( GET or POST )
	type: "GET",
        // the URL to which the request is sent
	url: mw.util.wikiScript('api'),
        // data to be sent to the server
	data: { action:'query', format:'json', lgname:'foo', lgpassword:'foobar' },
        // The type of data that you're expecting back from the server
	dataType: 'json',
        // Function to be called if the request succeeds
	success: function( jsondata ){
		alert( jsondata.result );

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:

whatLinksHere = JSON.parse(
        data: { action: 'query', format: 'json', list: 'embeddedin', eititle: 'Template:' + templateName, eilimit: 500 },

// ... usage ...
for (i=0; i<whatLinksHere.query.embeddedin.length; i+=1) {

(JSON.parse() 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 — 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).

    url: '//',
    data: {
        format: 'json'
    dataType: 'jsonp'
}).done( function ( data ) {
} );

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. Don't use it, use jQuery.ajax() instead. Some extensions, whether using Sajax or not, make Ajax calls through the obsolete AjaxDispatcher (see $wgAjaxExportList) by invoking index.php?action=ajax&rs=something.... They should instead make MediaWiki API requests to API modules api.php?action=something.

See also

External links

General information on XMLHttpRequest: