所以我制作了一个PHP脚本来输出json中的推文,现在我试图用javascript解析数据。我测试了数据,它是有效的json。当我在示例2中执行请求时,它工作正常。当我尝试使用示例1解析时,它无法说Uncaught SyntaxError: Unexpected token N
。我的问题是什么?
示例1
var request = $.ajax({
url: "http://website.com/twitter.php",
type: "GET",
data: {
twitter: 'google'
},
dataType: "json"
});
request.done(function(data) {
var resp = JSON.parse(data);
console.log(resp);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
示例2
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.com/twitter.php?twitter=google", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
console.log(resp);
}
};
xhr.send();
JSON数据
["New Google Trends features\u2014including Trending Top Charts\u2014make it easier to explore hot topics in #GoogleSearch g.co\/jmv6","Stating now, join our Hangout w\/ President Barroso on the #SOTEU goo.gl\/FZCXaJ #askbarroso","Explore the Galapagos Islands + see sea lions, blue-footed boobies & other animals w\/ Street View in @googlemaps g.co\/ufjq","Slow connections may keep Google Instant (results as you type) from working smoothly. Our troubleshooting tip: g.co\/bve7","From @BBCNews: search VP Ben Gomes on how search has become more intuitive & the next frontier (includes video) goo.gl\/Z0ESkJ","\"Audio Ammunition\" - an exclusive 5-part documentary about the Clash from @GooglePlay g.co\/zrxn & on youtube.com\/googleplay","justareflektor.com\u2013\u2013an interactive @ChromeExp HTML5 film with @arcadefire, featuring their new single, \u201cReflektor\u201d","#askbarroso about the State of the European Union in a live conversation Thurs, Sept 12 g.co\/n3tj","Don\u2019t get locked out: set up recovery options for your Google Account now g.co\/sm4k","It's time for more transparency: our amended petition to the the U.S. Foreign Surveillance Court g.co\/gkww"]
答案 0 :(得分:4)
由于您的数据类型为json
,因此已完成回调中的data
已经被解析,因此尝试再次解析它会导致错误。
request.done(function(data) {
//var resp = JSON.parse(data);
console.log(data);
});
答案 1 :(得分:1)
jQuery的.ajax
会自动解析JSON响应,因此不应单独调用.parse
。使用以下内容:
$.ajax({
url: "http://example.com/twitter.php",
type: "GET",
data: {
twitter: 'google'
},
dataType: "JSON",
success : function(JSON,jqXHR){
console.log(JSON.value); /* value of value */
console.log(jqXHR.responseText); /* all returned */
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request failed: " + textStatus);
}
});