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

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

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

回答1:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!