4

我正在向GETGreasemonkey 发出请求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);
      }
    }); 


这是服务器代码ytube.php

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

$_REQUEST=> 返回一些与 WordPress 相关的数据。 $_GET=> 返回一个空白数组。

我不知道出了什么问题。我什至也试过这个POST方法。

4

1 回答 1

5

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

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


如果要发送大量数据或复杂数据,请使用 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.
    }, 
    ... ...
} ); 

你的 PHP 会像这样访问它:

$jsonData   = json_decode($HTTP_RAW_POST_DATA);

更新:
Greasemonkey 和 Tampermonkey 现在要求您在元数据块中进行设置。@grant GM_xmlhttpRequest一定要这样做。

于 2012-02-22T22:18:06.050 回答