![](/img/trans.png)
[英]SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
[英]parsing json error : SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
從php將json解析為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上找到的解決方案,但仍然無法解決此問題
請有人幫忙
謝謝
如果響應為JSON,則jQuery的$ .ajax()函數將生成一個JavaScript對象,因此我認為您看到的錯誤是嘗試解析JavaScript對象而不是您期望的字符串的結果。 在提供給done
函數的回調中,檢查data
,您會發現它是一個對象,不需要JSON.parse
結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.