www*_*.me 4 php ajax json greasemonkey tampermonkey
我正在向GET
Greasemonkey发出请求GM_xmlhttpRequest()
:
$(".getReview").click(function(){
var videoId = $(this).parents("li").find("a").attr("href");
alert(videoId);
GM_xmlhttpRequest({
method: "GET",
url: "http://www.amitpatil.me/demos/ytube.php",
data: "username=johndoe&password=xyz123",
headers: {
"User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used.
"Accept": "text/xml" // If not specified, browser defaults will be used.
},
onload: function(response) {
console.log(response);
}
});
Run Code Online (Sandbox Code Playgroud)
这是服务器代码ytube.php:
<?php
print_r($_REQUEST);
print_r($_GET);
echo "Hello friends".$_GET['vid'];
?>
Run Code Online (Sandbox Code Playgroud)
$_REQUEST
=>返回与WordPress相关的一些数据.
$_GET
=>返回一个空数组.
我无法弄清楚出了什么问题.我甚至尝试过这种POST
方法.
该data
参数仅适用于POST
方法.如果您希望通过GET
请求发送数据,请将其附加到URL:
GM_xmlhttpRequest ( {
method: "GET",
url: "http://www.amitpatil.me/demos/ytube.php?username=johndoe&password=xyz123",
// Use no data: argument with a GET request.
... ...
} );
Run Code Online (Sandbox Code Playgroud)
但POST
出于各种原因,最好通过数据发送数据.为此,您需要指定编码:
GM_xmlhttpRequest ( {
method: "POST",
url: "http://www.amitpatil.me/demos/ytube.php",
data: "username=johndoe&password=xyz123",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used.
"Accept": "text/xml" // If not specified, browser defaults will be used.
},
... ...
} );
Run Code Online (Sandbox Code Playgroud)
如果要发送大量数据或复杂数据,请使用JSON:
var ajaxDataObj = {
u: username,
p: password,
vidInfo: [123, "LOLcats Terrorize City!", "Five stars"]
};
var serializedData = JSON.stringify (ajaxDataObj);
GM_xmlhttpRequest ( {
method: "POST",
url: "http://www.amitpatil.me/demos/ytube.php",
data: serializedData,
headers: {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used.
"Accept": "text/xml" // If not specified, browser defaults will be used.
},
... ...
} );
Run Code Online (Sandbox Code Playgroud)
您的PHP会像这样访问它:
$jsonData = json_decode($HTTP_RAW_POST_DATA);
Run Code Online (Sandbox Code Playgroud)
更新:
Greasemonkey和Tampermonkey现在要求您在元数据块中设置@grant GM_xmlhttpRequest
.一定要这样做.