문제

My script does not work. The AJAX call is not happening. Why?

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


I listed the API function in a @grant directive, but I do not see an AJAX call and response.

도움이 되었습니까?

해결책

See the documents for GM_xmlhttpRequest(). data takes only a string.

If you try to send non-string data to data, you will get an error like:

Component does not have requested interface
(113 out of range 67)

So, you must encode data into an appropriate string. Also, you will need to send the appropriate Content-Type header. The two main types/methods are:

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

Encoding and sending the data looks like this for the two methods:

Form-encoded data:

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 serialized data:

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);
    }
} );
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top