Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
909 views
in Technique[技术] by (71.8m points)

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

i have a problem when parsing json from php to javascript

this is my example code :

//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

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

please someone help

thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...