1

这与问题非常相似,例如:Request to Random.org API with ZendFramework2
但是,我认为我的问题出在我的数据请求中。

GM_xmlhttpRequest({
    method: "POST",
    url: "https://api.random.org/json-rpc/1/invoke",
    data: {
        "jsonrpc": "2.0",
        "method": "generateDecimalFractions",
        "params": "{\"apiKey\": \"d2319b89-8389-4d24-b1eb-4dbd80009153\",\"n\": 10,\"decimalPlaces\": 8,\"replacement\": true}",
        "id": 15324815
    },
    headers:{
        "Content-Type": "application/json-rpc"
    },
    onload: function(response) {
        console.log(response);
    }
});

我得到的错误是:

finalUrl: "https://api.random.org/json-rpc/1/invoke"
readyState: 4
响应: "{"jsonrpc": "2.0", "error": {"code": -32700, "message “:“解析错误”,“数据”:null},“id”:null}”
responseHeaders:“日期:周三,2015 年 4 月 1 日 02:34:08 GMT?服务器:Apache/2.2.22 (Debian)?X -Powered-By: PHP/5.4.39-0+deb7u2?Content-Type: application/json; charset=utf-8?Access-Control-Allow-Origin:
*?Connection: Keep-Alive?Access-Control-Allow -Headers: Origin, X-Requested-With, Content-Type, Accept?Content-Length: 87?Keep-Alive: timeout=15, max=200?"
responseText: "{"jsonrpc": "2.0", "error": {"code": -32700, "message":


所以我相当肯定问题出在我的 JSON 请求中。我希望对 JSON-RPC 有更多经验的人可以帮助我指出正确的方向。

4

1 回答 1

0

您需要在发送数据之前对数据进行正确的 JSON 编码:

var encodedData = JSON.stringify ( {
    "jsonrpc": "2.0",
    "method": "generateDecimalFractions",
    "params": {apiKey: "d2319b89-8389-4d24-b1eb-4dbd80009153", n: 10, decimalPlaces: 8, replacement: true},
    "id": 15324815
} ); 

GM_xmlhttpRequest ( {
    method:     "POST",
    url:        "https://api.random.org/json-rpc/1/invoke",
    data:       encodedData,
    headers:    {
        "Content-Type": "application/json"
    },
    onload:     function (response) {
        console.log (response);
    }
} );
于 2015-04-02T11:28:44.743 回答