【问题标题】:parsing json error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data解析 json 错误:SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
【发布时间】:2015-03-05 10:34:36
【问题描述】:

我在将 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 找到的解决方案,但仍然无法解决这个问题

请人帮忙

谢谢

【问题讨论】:

    标签: php jquery json


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2016-05-16
      • 1970-01-01
      • 2018-02-03
      • 2019-01-31
      • 1970-01-01
      相关资源
      最近更新 更多