我通过将数组传递到PHP的json_enocode()
来使用ajay从服务器获取一些JSON数据,它返回了一个有效的JSON(在许多在线JSON调试器上检查过)。但JS的$.parseJSON()
不接受它。解析器为一组数据抛出错误(下面),同时它适用于其他数据集。
CONSOLE> SyntaxError:JSON.parse:JSON数据的第1行第1列的意外字符
我尝试逐个删除数组的所有元素,但即使使用单个元素也无法工作。以下是数据集:
这是有效的:
[{"id":"54a3b103877c0","act_name":"ABC","profile_image":"[\"551d\"]"}]
虽然这不是:
[{"id":"2","user_id":"53b595a","review_for_id":"54f25","review_for_type":"city",
"r_title":"asfasas asd as","r_body":"a sdasda sdas dasdas das d","r_rating":"3",
"other_info":"","added":"2015-03-28 15:47:20","modified":"2015-03-28 15:47:20",
"f_name":"ABC","l_name":"XYZ","lives_in":"ABC"}]
PHP代码:
阵列:
Array
(
[0] => Array
(
[id] => 2
[user_id] => 53b595a
[review_for_id] => 54f25
[review_for_type] => city
[r_title] => asfasas asd as
[r_body] => a sdasda sdas dasdas das d
[r_rating] => 3
[other_info] =>
[added] => 2015-03-28 15:47:20
[modified] => 2015-03-28 15:47:20
[f_name] => ABC
[l_name] => XYZ
[lives_in] => ABC
)
)
PHP-上面的数组有$ d
json_encode($d, JSON_HEX_TAG | JSON_HEX_QUOT)
以下是Ajax的Jquery:
$.get(url, '', function(d){
var data = {};
if(d != ''){
data = $.parseJSON(d);
}
var acc = {};
acc[sc_id] = data;
console.log(acc);
});
请帮忙!
答案 0 :(得分:1)
<script>
var str = '[{"id":"2","user_id":"53b595a","review_for_id":"54f25","review_for_type":"city","r_title":"asfasas asd as","r_body":"a sdasda sdas dasdas das d","r_rating":"3","other_info":"","added":"2015-03-28 15:47:20","modified":"2015-03-28 15:47:20","f_name":"ABC","l_name":"XYZ","lives_in":"ABC"}]';
var obj = $.parseJSON(str);
alert(obj.id);
</script>
答案 1 :(得分:0)
有时从PHP可以使用json_encode函数或带有JSON格式和application / json标头的纯文本将JSON数据发送到AJAX调用。因此,检查AJAX响应是否已成为对象是一个更好的主意。
var data = {};
if (typeof response !== 'object') {
data = $.parseJSON(response);
} else {
data = response;
}
这样可以防止输入错误。