【发布时间】:2017-02-10 06:05:20
【问题描述】:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
</head>
<script>
function newQuote() {
$.ajax({
type: "GET",
url: "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1",
success: function(data) {
//console.log('success', data);
quote = JSON.parse(data);
$('#content').html(quote[0].content);
$('#author').html(quote[0].title);
}
});
}
$(document).ready(function() {
var quote;
newQuote();
$('#getQuote').click(function(event) {
newQuote();
});
});
</script>
<body>
<div class="container-fluid">
<div class="row text-center">
<h1>Random Quote Machine</h1>
</div>
<div class="row text-center">
<div class="well" id="content">
The quote will go here
</div>
<div id="author">The author will go here </div>
<div class="row text-center">
<button id="getQuote" class="btn btn-primary">Get Quote </button>
</div>
</div>
</body>
我正在尝试使用 AJAX 制作一个随机报价机来向 API 请求,但是当我单击标有 get quote 的按钮时,什么也没有发生。我的 AJAX 请求有什么问题?是不是语法错了?
编辑:我实施了建议的更改,但它仍然不起作用。这是我控制台上的错误消息:
未捕获的 SyntaxError:位置 1 处 JSON 中的意外标记 o
在 JSON.parse()
在 Object.success (VM333 pen.js:7)
在 j (jquery.min.js:2)
在 Object.fireWith [as resolveWith] (jquery.min.js:2)
在 x (jquery.min.js:4)
在 XMLHttpRequest。 (jquery.min.js:4)
【问题讨论】:
-
检查控制台。并确保您的
API(url) 是正确的。 -
您的 API 返回一个带有值数组的 JSON。尝试使用
quote[0].content -
你为什么在 HTML 和 Javascript 中多次调用 newQuote?
标签: javascript jquery html ajax