2011-03-25 69 views
-1

我正在使用AJAX從數據庫中獲取值。 我正在使用JSON.parse不起作用

echo json_encode($writers); 

in php。

在我的呼喚

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

我得到結果的JScript

[{"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); 

我得到錯誤 誰能plz幫助,並解釋如何,我可以解決這個

感謝

我使用Firefox和螢火蟲它只是顯示錯誤的JSON.parse

+5

**你得到了什麼**錯誤? – Quentin 2011-03-25 07:18:49

+0

「我得到錯誤」不是診斷。 – 2011-03-25 07:19:02

+0

什麼瀏覽器會出錯? – 2011-03-25 07:22:26

回答

1

設置適當的內容類型,在PHP中:

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

儘管應該完成這個工作,但並不清楚它並沒有什麼區別,因爲瀏覽器最終會以xhr.responseText中的一個未分類的字符串結束。 – Quentin 2011-03-25 07:22:17

+0

爲什麼選擇投票? – 2011-03-25 07:34:12

+0

我第二... – 2011-03-25 09:04:08

1

仔細檢查使用jsonLint

我快速複製並粘貼您的JSON到它,並得到了一些錯誤,你的JSON - 確保日ere在json字符串中沒有換行符,因爲這會使json無效。