【问题标题】:Greasemonkey AJAX request is not sending data?Greasemonkey AJAX 请求没有发送数据?
【发布时间】:2012-03-13 03:32:34
【问题描述】:

我正在使用 Greasemonkey 的 GM_xmlhttpRequest() 发出 GET 请求:

$(".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 方法。

【问题讨论】:

    标签: php ajax json greasemonkey tampermonkey


    【解决方案1】:

    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 现在要求您在元数据块中输入 set @grant GM_xmlhttpRequest。请务必这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多