jQuery AJAX适用于Tampermonkey和Greasemonkey,与jQuery在网页中使用相比,只有一个限制。
例如,这种跨域脚本都Tampermonkey和Greasemonkey的工作原理:
// ==UserScript==
// @name _Demonstrate jQuery AJAX from Tampermonkey
// @include https://stackoverflow.com/questions/18546180/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
$.ajax ({
type: 'GET',
url: 'https://api.stackexchange.com/2.1/users/621338?site=stackoverflow&filter=!)2R0ltXnW6.fyPDiHJm',
dataType: 'JSON',
success: function (apiJson) {
var resultObj = apiJson.items[0];
alert (
'User ' + resultObj.display_name
+ ' has accept rate of ' + resultObj.accept_rate + '%.'
);
}
});
重要:
目标URL必须是同一个域,或者目标服务器必须有 合适的CORS值设置。
对于不支持跨域的服务器,您必须为您的AJAX使用GM_xmlhttpRequest()Doc。
由于沙盒和范围问题,JSONP是一个特例。
避免使用JSONP,或者使用this approach,或者询问一个新的问题具体的问题。