【问题标题】:Looping through JSON array from an API, can get all results or none result, no luck with loops, using jQuery从 API 循环遍历 JSON 数组,可以获得所有结果或没有结果,循环不走运,使用 jQuery
【发布时间】:2021-08-07 05:08:57
【问题描述】:

我只是在尝试一些新的东西来获得最新的技能,并且对这个 jQuery API 响应有点难过。我的所有结果都可以正常显示,我让它们显示在一个 html 文件上,但它们都作为一个整体。我想在每个单词之间打断(它是 [Words API][1],我被卡住了。我通常使用 PHP,但是,这对于我的计划来说并不实用。这是代码,我我会在结果中显示出最好的结果。谢谢!

   <div id="div1">
    // This is where it shows up as "unmitigated,butcherly,crimson,gory,homicidal,internecine"        
     </div>
   <script>  
const settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://wordsapiv1.p.rapidapi.com/words/bloody/similarTo",
    "method": "GET",
    "headers": {
    "x-rapidapi-key": "<my key>",
    "x-rapidapi-host": "<host>"
    }
 };

$.ajax(settings).done(function (response) {
    console.log(response);
      $("#div1").html(response.similarTo + " "); // This puts a comma between each word, but no spacing, when I want a line break. I need to be able to customize results, make them links, add styles, etc.
});

非常感谢!只有 3 周严格的“待在家里”Covid19 命令。我学到了很多东西!

【问题讨论】:

  • 嗨,你能显示response的输出吗?

标签: html jquery api


【解决方案1】:

我猜你在response.similarTo 中有一个文本字符串,其中包含一堆逗号分隔的单词。

您可以像这样处理它们。 Split 以逗号分隔它们。此代码的其余部分将它们格式化为 HTML 列表并显示它们。

const results = []
const words = response.similarTo.split(',')
for (const word of words) {
  /* do what you will with each word in turn, for example... */
  results.push('<li>' + word + '</li>')
}
$("#div1").html('<ol>' + results.join('') + '</ol>')

【讨论】:

  • 它在控制台中工作,但不幸的是,我在该行上收到“Uncaught TypeError: response.similarTo.split is not a function”。我正在四处寻找一些修复方法,仍在尝试。感谢您迄今为止的帮助!
  • 您的 TypeError 意味着 response.similarTo 不是字符串:它没有 .split() 方法。执行console.log(response),检查response 对象,并确保您了解其内容。
猜你喜欢
  • 1970-01-01
  • 2011-01-03
  • 2018-06-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2013-09-14
  • 2019-02-18
  • 1970-01-01
相关资源
最近更新 更多