Manual:Ajax
Esta página está desatualizada. |
Ajax é um termo usado para quando o JavaScript carrega partes da página sob demanda.
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 $ajax).
Detalhes
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:
$.ajax({
// 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(
$.ajax({
url:mw.util.wikiScript('api'),
data: { action: 'query', format: 'json', list: 'embeddedin', eititle: 'Template:' + templateName, eilimit: 500 },
async: false
})
.responseText
);
// ... usage ...
for (i=0; i<whatLinksHere.query.embeddedin.length; i+=1) {
alert(whatLinksHere.query.embeddedin[i]);
}
(JSON.parse()
is a JavaScript standard function that returns an object from its string representation in JSON format.)
Cross-wiki request
If you want to get data from a wiki that is hosted at a different domain than the current one, you will have to use Cross-Origin Resource Sharing (CORS) to make the request.
Most of the time, adding origin=*
to the request parameters should be sufficient.
See also
- Category:Ajax extensions - Extensions that use the Ajax interface of MediaWiki.
External links
- mediawiki.api (JavaScript module)
- jQuery.ajax (jQuery method)
General information on XMLHttpRequest:
- XMLHttpRequest specification at W3.org
- XMLHttpRequest on Wikipedia
- XMLHttpRequest on MDN