Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...