【问题标题】:why this jquery is not displaying the json response为什么这个 jquery 不显示 json 响应
【发布时间】:2017-06-21 16:50:51
【问题描述】:

我有一个 jquery 脚本从 api 中提取报价,并且数据以 json 格式返回。然后我试图在页面上显示输出。但由于某种原因,我无法从 api 获取数据。我在这里做错了什么? 谢谢

<html>
<head>
<title>Qoute Machine</title>
  <script>
    $(document).ready(function() {
  $("#getMessage").on("click", function(){
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
  $("#quote").html(JSON.stringify(a.content + " " + a.title));
});
});
  </script>
</head>
<body>
<h1>Welcome to Random Quotes!</h1>
<p>Press the button to display a quote!.</p>
  <button id="getMessage" type="button" onclick="getQuote();">Get quote</button>
  <p id="quote"></p>

</body>
</html>

【问题讨论】:

  • 控制台有什么错误吗?
  • 当您调试它时,a 是否包含您期望的内容?它包含什么?
  • 这个页面是否在 origin (quotesondesign.com) 内?
  • 我正在尝试在我的函数中使用 console.log(a.content),但没有任何显示... console.log() 在 jquery 中工作吗?将其记录到控制台的好方法是什么,所以我可以看到我得到的结果?顺便说一句,这是应该通过 ajax 完成的,还是可以使用 jquery json object reques 完成的?感谢您的帮助
  • @miatech:是的,console.log() 在 JavaScript 中工作。如果没有为 a.content 记录任何内容,则 a.content 不包含任何内容。

标签: jquery html json api


【解决方案1】:

a 已经被解析为 JSON,因此您无需将其字符串化以输出两个由空格分隔的 a 属性。事实上,这甚至都不是有效的 JSON。

您正在尝试对非 JSON 进行字符串化。只需使用:

$("#quote").html(a.content + " " + a.title);

但是,请在下面的 sn-p 中注意该请求存在跨域问题:

$("#getMessage").on("click", function() {
    $.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
      $("#quote").html(a.content + " " + a.title);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Welcome to Random Quotes!</h1>
<p>Press the button to display a quote!.</p>
<button id="getMessage" type="button">Get quote</button>
<p id="quote"></p>

【讨论】:

  • 这是应该在 jquery 中使用 ajax 或 json api 完成的吗?谢谢
【解决方案2】:

它在代码末尾缺少});,您不需要JSON.stringify,因为getJSON 返回json 或javascript 对象,您也不需要onclick="getQuote();",因为它已经由jQuery $("#getMessage").on("click" 处理。最后一个,如果它从不同的域访问,那么你需要启用跨域(CORS)

演示,允许 CORS:https://jsfiddle.net/ng5ut2L5/1/

下面,stackoverflow 是不允许的 CORS

$(document).ready(function() {
  $("#getMessage").on("click", function() {
    $.getJSON("//quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
      $("#quote").html(a[0].content + " " + a[0].title);
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1>Welcome to Random Quotes!</h1>
<p>Press the button to display a quote!.</p>
<button id="getMessage" type="button">Get quote</button>
<p id="quote"></p>

【讨论】:

  • 什么浏览器?你可以在行动中查看它i.stack.imgur.com/CKzg1.gif
  • 你是怎么得到它的?我一直在玩这段代码,但无法让这件事继续下去。不会那么难。
  • 你上面的链接..它在 jsfiddle 中打开,但是它没有运行。我知道 gif 图像有效。显然代码运行得很好。
猜你喜欢
  • 2012-01-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
相关资源
最近更新 更多