解析json错误:SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符 [英] parsing json error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

查看:1353
本文介绍了解析json错误:SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将json从php解析为javascript时遇到问题

i have a problem when parsing json from php to 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上找到的解决方案,但仍然无法解决此问题

how to solve this probled, i have try the solution that i found at SO and google, but still cannot solve this problem

请某人帮助

谢谢

推荐答案

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

jQuery's $.ajax() function will yield a JavaScript object if the response is JSON so I believe the error you're seeing is a result of trying to parse a JavaScript object and not a string as you're expecting. In the callback you're providing to the done function, inspect data and you'll find that it's an object and there is no need to JSON.parse the result.

这篇关于解析json错误:SyntaxError:JSON.parse:JSON数据第1行第2列的意外字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆