Wikipedia:WikiProject User scripts/Guide/Ajax: Difference between revisions
Content deleted Content added
→Code: fix links |
→Basic examples: Added example of how to get the wikicode of a page and links to "mediawiki.api" and "mediawiki.api.edit" modules |
||
Line 9:
* AJAX scripts cannot reach a page on a different server (for example, ''google.ca'' or ''en.wikisource.org'' from ''en.wikipedia.org''). Trying to do so will cause the script to halt with or without error. This can be circumvented using a proxy on the current server, but none is available for Wikimedia user scripts.
==
MediaWiki provides some modules with helper funtions which facilitate the use of its API. The main modules available are
===Fetch page content===▼
* [https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/resources/mediawiki.api/mediawiki.api.js?view=markup mediawiki.api]
* [https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/resources/mediawiki.api/mediawiki.api.edit.js?view=markup mediawiki.api.edit]
If your script makes use any method or code provided by these modules, remember to indicate the dependencies with [[mw:ResourceLoader/Default_modules#mediaWiki.loader|mw.loader.using]] or, in case of gadgets, on its definition at [[MediaWiki:Gadgets-definition]].
▲=== Fetch page content ===
Fetching a page content can be done using [[GET]].
<source lang="javascript">
$.ajax({
url: mw.util.wikiGetlink( 'Wikipedia:Sandbox' ),
success: function( data ) {
alert( 'The remote page contains:\n' + data );
Line 23 ⟶ 28:
});
</source>
=== Get the wikicode of a page ===
<source lang="javascript">
var api = new mw.Api();
api.get( {
action: 'query',
prop: 'revisions',
rvprop: 'content',
rvlimit: 1,
indexpageids: true,
titles: 'Wikipedia:Sandbox'
}, {
ok: function ( data ) {
var q = data.query,
id = q && q.pageids && q.pageids[0],
pg = id && q.pages && q.pages[ id ],
rv = pg && pg.revisions;
if ( rv && rv[0] && rv[0]['*'] ) {
alert( 'The wikicode of the page "' + pg.title + '" is:\n\n' + rv[0]['*'] );
}
}
} );
</source>
===Edit a page and other common actions===
Scripts can perform common actions (like editing, protection, blocking, deletion, etc.) through the [{{SERVER}}/w/api.php API]. These actions require an edit token, which is valid for any action during the same session. (However, you should get a new token for different tasks in case this changes in the future.)
|