【问题标题】:.getJSON() callback wont work but API's url works fine.getJSON() 回调不起作用,但 API 的 url 工作正常
【发布时间】:2017-11-25 00:10:24
【问题描述】:

我正在尝试通过使用 API 来了解有关 API 的更多信息,但我现在在使用 Flickr API 时遇到了问题。

当我手动将其输入到 chrome 中并返回 JSON 时,我进入 .getJSON() 的 URL 工作正常,但下面代码中的回调函数不起作用,这意味着 .getJSON(url) 不起作用。

let city='boston';

function gettingFlickrJSON(city1){
    city = city1;
    console.log(1);
    $.getJSON('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[my_key_which_i_left_out_for_now]&tags='+city+',city&per_page=10&format=json',function(json){
      console.log(2);
    });
}

我试着拿出来

&tags='+city+',city... 

并替换为示例运行,回调仍然不起作用。 我 99% 确信该链接有效,因为正如我所说,手动输入时它有效。是的,我已将 jquery 导入到我的脚本中。 如果有任何帮助,这是我尝试使用的方法的文档链接。 https://www.flickr.com/services/api/flickr.photos.search.html

【问题讨论】:

  • 有什么错误吗?在“网络”选项卡中获取的 JSON 是否没有错误?
  • @Xufox 是的,我是网络选项卡的新手,但它显示状态:200,就像我的 jquery 文件一样
  • 您在 Chrome 中使用的示例网址是什么?
  • 检查jQuery函数是否用console.log(typeof $ == 'function');

标签: javascript jquery json api


【解决方案1】:

如果您打算将这样的响应与$.getJSON 一起使用,则需要在请求中使用参数jsonnocallback=1,否则您必须覆盖响应方法,然后根据需要对其进行操作。

基本上,您将JSON 字符串误解为JSONCallbackfunction

用于观察使用或不使用此parameter 时两个响应之间的区别。

打开两个窗口withwithout附加这个参数。你会发现一个返回JSON字符串,另一个返回回调函数jsonFlickrApi(response),其中包含一个JSON对象作为参数。我已经添加了您的代码的示例代码 sn-p 以及我的 API 键,只是为了确保它对您有用,如果它对您有用,我会在您回复后删除。

如果您想了解使用回调函数的更安全的方法,请参阅here

let city = 'boston';

$(document).ready(function() {
  $("#findnow").click(function() {
    $.getJSON('https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[insert_api_key]&tags=' + city + ',city&per_page=50&format=json&nojsoncallback=1', function(res) {
      for (var key in res.photos.photo) {
        $("#results").append("<li><span class='label label-primary'>" + res.photos.photo[key]['title'] + "</span></li>");
      }
    })

  });
})
* {
  margin: 20px auto;
}

body {
  text-align: center;
}

.container {
  border: 2px dashed #000;
  max-height: 250px;
  max-width: 85%;
  overflow-x: hidden;
  overflow-y: scroll;
  text-align: left;
}

ul,
li {
  margin: 0;
  padding: 0;
  list-style-type: none;
  display: block;
  line-height: normal;
  margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<button id="findnow" class="btn btn-default">find photos</button>

<div class="container">
  <p>Below are the list of the photos</p>
  <ul id="results">
  </ul>
</div>

【讨论】:

    猜你喜欢
    • 2015-01-16
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    • 2018-11-23
    • 1970-01-01
    相关资源
    最近更新 更多