2013-01-05 21 views
1

我的腳本不起作用。 AJAX調用沒有發生。爲什麼?Greasemonkey AJAX帖子似乎無法正常工作,即使指定了@grant

// ==UserScript== 
// @name  prova 
// @namespace http://blogpagliaccio.wordpress.com/ 
// @description prova 
// @include  http://* 
// @version  1 
// @grant  GM_xmlhttpRequest 
// @require  http://userscripts.org/scripts/source/85398.user.js 
// ==/UserScript== 

// [........... other code] 

    console.log('start ajax call...'); 
      GM_xmlhttpRequest({ 
        method: "POST", 
        url: "www.prova.it", 
        data: {parametro:parametro}, 
        onload: function(response) { 
          console.log(response.responseText); 
        }, 
        onerror: function(reponse) { 
          alert('error'); 
          console.log(reponse); 
        } 
      }); 


我在@grant指令中列出的API函數,但我沒有看到一個AJAX調用和響應。

回答

4

請參閱the documents for GM_xmlhttpRequest()data只需要一個字符串

如果您嘗試非字符串數據發送到data,你會得到這樣的錯誤:

組件沒有請求的接口
(113超出範圍67)

所以,你必須將數據編碼成適當的字符串。另外,您需要發送相應的Content-Type標題。兩種主要類型/方法有:

  1. application/x-www-form-urlencoded
  2. application/json

編碼和發送的數據是這樣的兩種方法:

表單的編碼數據:

GM_xmlhttpRequest ({ 
    method:  "POST", 
    url:  "www.prova.it", 
    data:  "parametro=" + encodeURIComponent (parametro), 
    headers: { 
     "Content-Type": "application/x-www-form-urlencoded" 
    }, 
    onload:  function (response) { 
     console.log(response.responseText); 
    }, 
    onerror: function(reponse) { 
     //alert('error'); 
     console.log("error: ", reponse); 
    } 
}); 


JSON序列數據:

GM_xmlhttpRequest ({ 
    method:  "POST", 
    url:  "www.prova.it", 
    data:  JSON.stringify ({parametro:parametro}), 
    headers: { 
     "Content-Type": "application/json" 
    }, 
    onload:  function (response) { 
     console.log(response.responseText); 
    }, 
    onerror: function(reponse) { 
     //alert('error'); 
     console.log("error: ", reponse); 
    } 
}); 
+0

感謝您的幫助 – pagliaccio