【问题标题】:Userscript AJAX request gives JSON-RPC error -32700用户脚本 AJAX 请求给出 JSON-RPC 错误 -32700
【发布时间】:2015-06-05 14:14:49
【问题描述】:

这与问题极为相似,例如: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"
就绪状态:4
响应:“{”jsonrpc”:“2.0”,“错误”:{“代码”:-32700,“消息”:“解析错误”,“数据”: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?内容类型:应用程序/ 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": "解析错误", "data": null}, "id": null}"
响应XML:空
状态:200
状态文本:“确定”

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

【问题讨论】:

    标签: json userscripts json-rpc gm-xmlhttprequest


    【解决方案1】:

    您需要在发送数据之前对数据进行正确的 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);
        }
    } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-24
      • 1970-01-01
      • 2017-06-17
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多