Greasemonkey AJAX request is not sending data?

2019-06-25 07:57发布

I am firing a GET request with Greasemonkey's 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);
      }
    }); 


and here is the server code ytube.php:

<?php
  print_r($_REQUEST);
  print_r($_GET);
  echo "Hello friends".$_GET['vid'];
?>

$_REQUEST => returns some data related to WordPress. $_GET => returns a blank array.

I can't figure out what's wrong. I even tried the POST method too.

1条回答
The star\"
2楼-- · 2019-06-25 08:38

The data parameter only works for POST methods. If you wish to send data with a GET request, append it to the 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.
    ... ...
} ); 

But it's better to send data via POST, for a variety of reasons. To do that, you need to specify an encoding:

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.
    }, 
    ... ...
} ); 


If you are going to send a lot of data, or complex data, use 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.
    }, 
    ... ...
} ); 

Your PHP would access it like so:

$jsonData   = json_decode($HTTP_RAW_POST_DATA);

Update:
Greasemonkey and Tampermonkey now require that you set @grant GM_xmlhttpRequest in the metadata block. Be sure to do that.

查看更多
登录 后发表回答