我想在我的Tampermonkey脚本中做一些AJAX操作,我发现jQuery相当方便。目前仍然没有办法让jQuery AJAX与Tampermonkey一起工作吗?
请注意,操作不会是相同的来源,这是使用Tampermonkey的全部原因。 Greasemonkey也行。
答案 0 :(得分:6)
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值。
对于非跨域友好的服务器,您必须使用GM_xmlhttpRequest()
Doc作为您的AJAX。
由于沙盒和范围问题,JSONP是一个特例 避免使用JSONP,或使用this approach,或针对 特定的 问题提出新问题。