JSON.parse无效

时间:2011-03-25 07:17:06

标签: php javascript ajax json

我正在使用AJAX从数据库中获取值。 我正在使用

echo json_encode($writers);

在php。

当我打电话给

时,在jscript中

document.getElementById("writer").innerHTML = xmlhttp.responseText;

我得到结果

[{"name":"demo-1","user_id":"13","writing_level":"","writing_category":"","pri":3},{"name":"Atif Rauf
Alvi","user_id":"12","writing_level":"High
 School","writing_category":"Social
 Sciences,History,Mathematics and
 Economics,Nature,Health and
 Medicine,Creative
 writing","pri":3},{"name":"ffffo","user_id":"14","writing_level":"High
 School,College,Masters","writing_category":"Literature
 and Language,Social
 Sciences,Mathematics and
 Economics","pri":3},{"name":"mariam","user_id":"15","writing_level":"High
 School","writing_category":"Communications
 and Media,Religion and Theology,Life
 Sciences,Creative
 writing","pri":3},{"name":"ddd","user_id":"17","writing_level":"High
 School,College","writing_category":"Literature
 and Language,Art,Social
 Sciences,History,Law","pri":3},{"name":"maria","user_id":"16","writing_level":"High
 School","writing_category":"Art,Social
 Sciences,History,Law,Mathematics and
 Economics","pri":3},{"name":"Muhammad
 Zoyeb","user_id":"11","writing_level":"High
 School,College","writing_category":"Education,Tourism","pri":3},{"name":"wewe","user_id":"10","writing_level":"","writing_category":"","pri":3},{"name":"janea","user_id":"5","writing_level":"","writing_category":"","pri":3},{"name":"shazia","user_id":"4","writing_level":"","writing_category":"","pri":3},{"name":"s","user_id":"6","writing_level":"","writing_category":"","pri":3},{"name":"iuiui","user_id":"8","writing_level":"","writing_category":"","pri":3},{"name":"demo","user_id":"9","writing_level":"","writing_category":"","pri":3},{"name":"arsalan","user_id":"3","writing_level":"","writing_category":"Nature,Education,Health and Medicine,Communications and Media","pri":3}]

是一个有效的json对象

但是当我使用

var writer=JSON.parse(xmlhttp.responseText);

我收到错误 任何人都可以帮助解释我如何解决这个问题

由于

我正在使用firefox,而在firebug中它只是在JSON.parse显示错误

2 个答案:

答案 0 :(得分:1)

在php中设置适当的内容类型:

header('Content-type: application/json');
echo json_encode($writers);

答案 1 :(得分:1)

使用jsonLint

仔细检查你的json

我快速复制并粘贴你的json并得到一些错误 - 确保json字符串中没有换行符,因为这会使json无效。