Javascript 如何使用GM_xmlhttpRequest提交到基本的外部表单页面?
我为Greasemonkey创建了一个基本脚本,以便在堆栈溢出上搜索单词Javascript 如何使用GM_xmlhttpRequest提交到基本的外部表单页面?,javascript,forms,greasemonkey,gm-xmlhttprequest,Javascript,Forms,Greasemonkey,Gm Xmlhttprequest,我为Greasemonkey创建了一个基本脚本,以便在堆栈溢出上搜索单词test 根据,请求的参数应在data参数中指示 // ==UserScript== // @name Test Search SO // @namespace Test Search SO // @description Test Search SO // @include http://YOUR_SERVER.COM/YOUR_PATH/* // @version 1 // @grant
test
根据,请求的参数应在data
参数中指示
// ==UserScript==
// @name Test Search SO
// @namespace Test Search SO
// @description Test Search SO
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @version 1
// @grant GM_xmlhttpRequest
// ==/UserScript==
alert("Ready?");
GM_xmlhttpRequest({
url: "http://stackoverflow.com/search",
method: "GET",
data: "q=test",
onload: function(response) {
document.getElementsByTagName("html")[0].innerHTML = response.responseText;
alert("Done.");
}
});
不幸的是,结果只是页面http://stackoverflow.com/search
就像忽略了数据一样
如何解决此问题?若要将数据发送到表单页,通常必须使用POST
要使用POST,通常还必须确保编码符合页面的预期
这项工作:
GM_xmlhttpRequest ( {
url: "http://stackoverflow.com/search",
method: "POST",
data: "q=" + encodeURIComponent ("test"),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function (response) {
document.getElementsByTagName ("html")[0].innerHTML = response.responseText;
alert ("Done.");
}
} );
(不要忘记对参数进行URI编码。)
或者,许多这样的页面将接受GET
请求,但随后您将数据作为URL参数发送:
GM_xmlhttpRequest ( {
url: "http://stackoverflow.com/search?q=" + encodeURIComponent ("test"),
method: "GET",
onload: function (response) {
document.getElementsByTagName ("html")[0].innerHTML = response.responseText;
alert ("Done.");
}
} );