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

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

我在将 json 从 php 解析为 javascript

时遇到问题

这是我的示例代码:

//function
MethodAjax = function (wsFile, param) {
    return $.ajax({
        type: "POST",
        dataType: "json",
        url: '../proses/' + wsFile + ".proses.php",
        data: 'param='+param,
        error: function (msg) {
            return;
        },
    });
};

//call function 
$(document).ready(function() {

    $('#getproduk').click(function(){
        var param = {
        ProdukId : '1',
        ProdukName : 'test'
    };

    CallMethodWithAjax('try', JSON.stringify(param)).done(function(data){
        $data =  JSON && JSON.parse(data) || $.parseJSON(data); 
    });
});

//Simple Php code
<?php
    $data = $_POST['param'];

    $data = (json_decode($data));

    $data1['name'] = $data->ProdukName;
    $data1['id'] = $data->ProdukId;
    $data1['test'] = 'test';


    echo json_encode($data1);
?>

//post, response and error at console
response : {"name":"test","id":"1","test":"test"}
post : param    {"ProdukId":"1","ProdukName":"test"}
error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON  data

如何解决这个问题,我已经尝试了我在SO和google上找到的解决方案,但仍然无法解决这个问题

请有人帮忙

感谢

jQuery 的 $.ajax() 函数将产生一个 JavaScript 对象,如果响应是 JSON 所以我相信你看到的错误是尝试的结果解析 JavaScript 对象而不是您期望的字符串。在您提供给 done 函数的回调中,检查 data 并且您会发现它是一个对象并且不需要 JSON.parse 结果。