2015-04-26 101 views
0

這是XMLHttpRequest對象。當我把它放在cosole.log它提供了以下回應:JSON解析問題與AJAX

console.log(this.responseText); 
"[ 
    { 
    "url": "https://api.github.com/gists/c7c0df592e99c0c34b99", 
    "forks_url": "https://api.github.com/gists/c7c0df592e99c0c34b99/forks", 
    "commits_url": "https://api.github.com/gists/c7c0df592e99c0c34b99/commits", 
    "id": "c7c0df592e99c0c34b99", 
    "git_pull_url": "https://gist.github.com/c7c0df592e99c0c34b99.git", 
    "git_push_url": "https://gist.github.com/c7c0df592e99c0c34b99.git", 
    "html_url": "https://gist.github.com/c7c0df592e99c0c34b99", 
    "files": { 
     "config.json": { 
     "filename": "config.json", 
     "type": "application/json", 
     "language": "JSON", 
     "raw_url": "https://gist.githubusercontent.com/anonymous/c7c0df592e99c0c34b99/raw/70489beaa4953f89fc8848195371da6eca76164c/config.json", 
     "size": 17911 
     } 
    }, 
    "public": true, 
    "created_at": "2015-04-26T20:34:11Z", 
    "updated_at": "2015-04-26T20:34:11Z", 
    "description": "Bootstrap Customizer Config", 
    "comments": 0, 
    "user": null, 
    "comments_url": "h"[…] 

但是當我嘗試使用就可以了JSON.parse它給了我一個錯誤:SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

要旨= JSON.parse(this.reponseText)

IM應該是使用此API https://developer.github.com/v3/gists/和它應該根據該文檔

在上述數據,是由返回的返回有效的JSON網站無效JSON?或者我應該使用JSON.parse以外的其他功能?或者發生了什麼?請幫忙。

全引擎收錄在這裏:http://pastebin.com/BWttNtXP

+0

這不是有效的JSON是爲什麼... ...這怎麼被生產?我們可以看到這些代碼嗎? –

+2

您需要將開始的引號替換爲單引號,因爲您的內引號是雙引號。 –

+2

@ChavdarSlavov - 這可能是JSON複製/粘貼的查看器的人造物。 – Quentin

回答

0

試試這個:)

console.log(this.responseText); 
    var txt = this.responseText.trim("\""); 
    gists = JSON.parse(txt); 

這樣你的HTML引擎收錄好的工作

3

更新:問題就迎刃而解了

問題的根源是代碼中的印刷錯誤。你能發現它嗎?

gists = JSON.parse(this.reponseText); 

更正:

gists = JSON.parse(this.responseText); 

OP的代碼,代碼工作正常,一旦此更改。

那麼,任何編碼了一段時間的人都知道,把一大堆時間浪費在像缺少括號或分號這樣簡單的事情上是多麼容易。當你終於找到它時......哦,哦!

原貼:

如下面的代碼是能夠拉和處理數據的罰款似乎沒有要什麼毛病JSON源。點擊「運行代碼片段」進行查看。

<!DOCTYPE HTML> 
 
<html> 
 
<head> 
 
<meta http-equiv="X-UA-Compatible" content="IE=10" /> 
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
 
<title>JSON</title> 
 
</head> 
 
<body> 
 
<h1 style="background-color:steelblue; color:white; padding:5px;">JSON DATA TEST</h1> 
 
Raw Data: 
 
<textarea id="output" style="width: 100%; height: 40em;padding:0.5em; border:1px black solid;"></textarea> 
 

 
<script type="text/javascript"> 
 
    // synchronous request for testing only. 
 
\t var xhr = new XMLHttpRequest(); 
 
\t xhr.open('GET', 'https://api.github.com/gists/public', false); 
 
\t xhr.send(); 
 
\t document.getElementById('output').value = xhr.responseText; 
 
\t 
 
\t try { 
 
\t \t var data = JSON.parse(xhr.responseText); 
 
\t \t alert('SUCCESS:\n' + data[0].forks_url); 
 
\t } 
 
\t catch(e){ alert('ERROR:\n' + e.description); } 
 
</script> 
 
</body> 
 
</html>

+0

aah ...這就是爲什麼我的代碼工作...但是啊...我沒有發現錯字:D –