2012-02-22 141 views
4

我燒成GET要求符合的Greasemonkey的GM_xmlhttpRequest()Greasemonkey AJAX請求沒有發送數據?

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

回答

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現在要求你set @grant GM_xmlhttpRequest在元數據塊。一定要這樣做。