【问题标题】:Greasemonkey AJAX post does not appear to work, even with @grant specified即使指定了@grant,Greasemonkey AJAX 帖子似乎也不起作用
【发布时间】:2013-01-05 19:12:58
【问题描述】:

我的脚本不起作用。 AJAX 调用没有发生。为什么?

// ==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 调用和响应。

【问题讨论】:

    标签: javascript http-post greasemonkey gm-xmlhttprequest


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-17
      • 2021-11-13
      • 2023-03-27
      • 2017-05-03
      • 1970-01-01
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多