【问题标题】:Cannot use 'in' operator to search for 'length' in不能使用 'in' 运算符搜索 'length' in
【发布时间】:2018-01-10 10:43:37
【问题描述】:

我读过this answer

我这样做了:

function countryPage() {
  $.ajax({
    url: "https://en.wikipedia.org/w/api.php?action=parse&disablelimitreport=true&format=json&prop=text|langlinks&noimages=true&mobileformat=true&page="+ curTitle + "&callback=?",
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    success: countryPageSuccess
  });
}

function countryPageSuccess(counterObject, data) {
  $.each(data, function(i, item) {...

但是如果我按照那个答案去做

 $.each(JSON.parse(data), function(i, item) {

我明白了

未捕获的 SyntaxError:位置 1 处 JSON 中的意外标记 o

【问题讨论】:

  • 登录 data 并查看它包含的内容,很可能它已经是一个对象
  • @PatrickEvans 好的,但如果我不这样做 JSON.parse 我会在问题标题中收到错误,是的,我确认它已经是一个对象
  • success 回调的第二个参数是 textStatus。它不会是 JSON。 JSON 响应应该已经在 counterObject 中反序列化
  • textStatus 是什么意思? @菲尔
  • 您从 API 获得的数据是第一个参数,而不是第二个参数(您称之为数据)。查看jQuery ajax 参考,了解成功回调是如何定义的

标签: javascript jquery json


【解决方案1】:

它已经是一个 JSON 对象。你不能再次解析它。

要接收HTTP错误代码,在success旁边提供一个错误回调函数,下面是我的代码。

function countryPage() {
  $.ajax({
    url: "https://en.wikipedia.org/w/api.php?action=parse&disablelimitreport=true&format=json&prop=text|langlinks&noimages=true&mobileformat=true&page=1&callback=?",
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    success: countryPageSuccess,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(jqXHR.status);
        alert(textStatus);
        alert(errorThrown);
    }
  });
}

function countryPageSuccess(data, result) {
    $.each(data, function(i, item) {
        console.log(item);
    });
}

countryPage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

  • 您能否删除控制台日志,以便我们通过$.each(data, function(i, item) { 获得完整的答案,即使将来参考?谢谢
  • 是的,但我们仍然有//$.each(JSON.parse(data), function(i,,即使被评论可能会让任何未来来到这里的用户感到困惑,应该有$.each(data, function(i, item) {
猜你喜欢
  • 1970-01-01
  • 2016-03-03
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
相关资源
最近更新 更多