【问题标题】:JSON data fetched using API not being displayed using JQuery and Handlebars使用 API 获取的 JSON 数据未使用 JQuery 和 Handlebars 显示
【发布时间】:2018-01-08 18:04:25
【问题描述】:

因此,我正在创建这个 web 应用程序,它利用 BetterDoctor 的 API 来获取与特定实践(如心脏病学)相关的医生列表。

我正在使用 Handlebars、JQuery、HTML 和 JS 来执行此操作。

A screenshot of what the code looks like in the browser

当我尝试在浏览器上运行代码时,在 {{#data}} 标记下的 HTML 页面中定义的模板中看不到数据。在检查页面并查看浏览器控制台时,我找不到任何错误,因为 console.log 正在返回正确的 url,其中包含要从中获取数据的所需 JSON 数据。

任何有关此问题的帮助都会非常有帮助,非常感谢。

这是一支包含代码的笔:https://codepen.io/sandeeprao/pen/OzbQJY?editors=1010

你可以看到错误

这是我的 HTML

<div>
  name a speciality: <input type="text" id="speciality">
<br></br>
  enter state (in short form): <input type="text" id="state">
  <br></br>
  lattitude: <input type="text" id="lat" value="">
  longitude: <input type="text" id="lon" value="">
</div>

<div id="content-placeholder"></div>
<script id="docs-template" type="text/x-handlebars-template">
 <table>
  <thead>
      <th>Name</th>
      <th>Title</th>
      <th>Bio</th>
  </thead>
  <tbody>
  {{#data}}
  <tr>
      <td><p>{{profile.first_name}} {{profile.last_name}}</p><br>
      <td>{{profile.title}}</td>
      <td>{{profile.bio}}</td>
  </tr>
  {{/data}}
  </tbody>
  </table>
 </script>

这是它的 JS 文件:

  var base_url = 'https://api.betterdoctor.com/2016-03-01/practices?';
  function go2(){
  var speciality = document.getElementById('speciality').value;
  var state = document.getElementById('state').value;
  var url_search = {
  name: speciality,
  location: state,
  user_location: '',
  skip: 0,
  limit: 10,
  user_key: 'CODE_SAMPLES_KEY_9d3608187'
   }
 console.log(speciality);
 console.log(state);
 var url = base_url + jQuery.param( url_search );
 console.log(url)
  $.get(url, function (data) {
  // data: { meta: {<metadata>}, data: {<array[Practice]>} }
  var template = Handlebars.compile(document.getElementById('docs-
  template').innerHTML);
  document.getElementById('content-placeholder').innerHTML = template(data);
   });
  }

【问题讨论】:

  • 不要使用以数字结尾的变量名。当您开始为变量编号时,这是一个很好的指标,表明您实际上想要使用数组。
  • 并且不要构建这样的 URL。曾经。这是不好的和错误的。 jQuery 有一个用于构建 URL 的辅助函数。阅读api.jquery.com/jquery.param
  • 请尝试将您的问题缩小到minimal reproducible example。例如,问题与 P5.js 有什么关系?如果没有,请删除 P5.js 代码和 p5.js 标记。尽可能使用硬编码值。发布指向显示问题的 CodePen 或 JSFiddle 的链接。祝你好运。
  • 嘿!谢谢回复!我确实听从了您关于删除 p5.js 部分的建议,并使其成为纯粹的 JS。关于 CodePen,我用上面的代码创建了一支笔,链接如下:codepen.io/sandeeprao/pen/OzbQJY?editors=1010
  • @Tomalak,我使用了数组而不是对变量进行编号。感谢您的提示!

标签: javascript jquery json api


【解决方案1】:

问题已解决。我发现把手代码和解释 API 结果的 JSON 格式存在问题。

<td>{{#doctors}}
    {{profile.first_name}}{{profile.last_name}}{{/doctors}}</td>
    <td>{{doctors.profile.first_name}} {{doctors.profile.last_name}}</td>

这就解决了!

【讨论】:

    猜你喜欢
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2021-01-13
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多