2012-02-22 40 views
4

私はグリースモンキーのGM_xmlhttpRequest()GET要求発射しています:Greasemonkey AJAXリクエストはデータを送信していませんか?

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

$_REQUEST =>はWordPressに関連するいくつかのデータを返します。

$(".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です。 $_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); 

更新:
グリースモンキーとTampermonkeyが今必要としますメタデータブロックでset @grant GM_xmlhttpRequest。それを必ず実行してください。

関連する問題