API:Cross-site requests/zh

If a user script or gadget needs to make an API call against another MediaWiki site (e.g. a script on the English Wikipedia needs to check image information on Commons), it must use JSONP or CORS.



JSONP 用法
The API's  accepts a   parameter, whose value is a JavaScript function which the JSON result will be wrapped in. This may be used to call the API on a remote site by dynamically adding tags to the document.

例子


GET请求


回应


CORS 用法
The MediaWiki API requires that the  be supplied as a query string parameter, with the value being the site from which the request originates, which is matched against the Origin header required by the CORS protocol. Note that this parameter must be included in any pre-flight request, and so should be included in the query string portion of the request URI even for POST requests.

When the  parameter is supplied and the request does not return a successful CORS response, MediaWiki≥1.30  will return a   header with a brief reason for the failure, e.g. in case of mismatched origin or unsupported headers in a   request header.

Unauthenticated CORS Requests
Unauthenticated CORS requests may be made from any origin by setting the  request parameter to. In this case MediaWiki will include the  header in the response and will process the request as if logged out.

例子


GET请求


Authenticated CORS Requests
To make an authenticated CORS request, the remote wiki's  setting must be set to allow the origin site. If the CORS origin check passes, MediaWiki will include the  header in the response, so authentication cookies may be sent.

contains more instructions and examples on how to handle CORS requests in JavaScript.



补充资料

 * Detailed differences between JSONP and CORS are available at CORS vs JSONP.

