简体   繁体   English

处理JSON响应时出错。 意外字符

[英]Error while processing a JSON Response. Unexpected character

I have a web service which returns the following Response/Payload: 我有一个Web服务,它返回以下响应/有效负载:

[{"msg":"Order requires backorder","status":"ERROR"}]

I have the following AJAX code to process this result: 我有以下AJAX代码来处理此结果:

$.post("/myorder/{{ order_id }}",
    {},
    function(data, status){
                    var dataJson = $.parseJSON(data);
                    if (status=="success") {
                            if (dataJson['status'] == "OK") {
                                    alert('Success');
                            } else {
                                    alert(dataJson['msg']);
                            }
                    } else {
                            alert("ERROR. Data: " + data + "\nStatus: " + status);
                    }
    }
);

Note: {{ order_id }} comes from used template system and it is not part of the question. 注意: {{ order_id }}来自二手模板系统,这不是问题的一部分。

I get the following error in the console: 我在控制台中收到以下错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

I have also tried not using .parseJSON and using directly variable data without sucess. 我也尝试过不使用.parseJSON并使用没有成功的直接变量data

Is .post the right method to use? .post是正确的使用方法吗? How could I further troubleshoot or what shall be done to process this JSON payload? 我如何进一步排除故障,或者应该怎么做才能处理此JSON有效负载?

First you do not need parseJSON since jQuery will parse it. 首先,您不需要parseJSON,因为jQuery会解析它。 Second you write your service returns an array with one object in there so using data.status would return undefined. 其次,您编写服务将返回一个数组,其中包含一个对象,因此使用data.status将返回未定义。 But using data[0].status and data[0].msg would work. 但是使用data [0] .status和data [0] .msg可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM