2015-04-26 107 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 –