0

所以我制作了一个 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"]
4

2 回答 2

4

Since you have json as your data type, data in your done callback will already be parsed so trying to parse it again is causing the error.

request.done(function(data) {
  //var resp = JSON.parse(data);

  console.log(data);
});
于 2013-09-12T20:01:32.483 回答
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);
  }
});
于 2013-09-12T20:02:30.063 回答