2016-03-08 124 views
3

我有一个PHP脚本像这样的2列意想不到的人物:parseJSON错误:第1行的JSON数据

$STL = array(); 
$filter = array(); 
$filter['sort_by'] = "date_added"; 
$filter['sale'] = "F"; 
$filter['per_page'] = "12"; 
$STL['filter'] = $filter; 
echo json_encode($STL); 

这给出了以下的输出:

{"filter":{"sort_by":"date_added","sale":"F","per_page":"12"}} 

我想使用parseJSON像这样:

$.ajax({ 
    url: 'myPHP.php', 
    type: 'post', 
    data : get_session, 
    async: false, 
    dataType: 'json', 
    success: function(result) { 
     var json = $.parseJSON(result);   
    } 
}); 

但我得到以下结果:

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

我猜json字符串在PHP中没有正确格式化。我错了什么?

回答

3

当您指定dataType: 'json'(或jQuery检测到JSON响应)时,它会自动为您解析JSON。如果您然后尝试再次解析生成的对象,则会看到您看到的错误。 success函数的result参数已经是您可以使用的对象。

另外请注意,您应该从未使用async: false。这是可怕的做法,因为它会阻止UI线程,直到AJAX请求完成。这看起来像浏览器崩溃的用户。从设置中移除该属性,并将所有依赖于AJAX结果的代码放在success处理程序中。

试试这个:

$.ajax({ 
    url: 'myPHP.php', 
    type: 'post', 
    data : get_session, 
    dataType: 'json', 
    success: function(result) { 
     console.log(result);  
    } 
}); 
+0

唉唉我给你!我在那里的菜鸟错误。这很棒,谢谢Rory。 – Lee

1

错误
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
发生在你的JSON对象是无效的。这种情况下,你可以通过jsonlint检查JSON,
但这种情况下,因为你的Ajax请求使用dataType: 'json'的,你的输出已经被解析josn

{"filter":{"sort_by":"date_added","sale":"F","per_page":"12"}}

$.parseJSON(result)转细绳JSON
您的请求响应已经是一个有效的JSON如此,$.parseJSON(string)返回错误

3

如果您使用$.parseJSON(result)已经成功的回调,然后雷莫ve dataType: 'json', from AJAX properties ..或者使用另一种方法保留dataType: 'json',因为您已经预期JSON,并删除$.parseJSON(result)。只使用其中一种。

相关问题