var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
$(document).ready(function() {
var $loader = $("#btn"),
$insertion=$("#insertionPoint");
$loader.click(function() {
$.ajax({
url:quoteUrl ,
dataType: 'json',
success:function(data){
var quote=data.quoteText;
$insertion.replaceWith('<p>'+quote+'</p>');
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Random quote Machine</h1>
<div id="insertionPoint">
<p>Quotes come here</p>
</div>
<button id="btn">Next Quote</button>
&#13;
任务:从forimastic.com的Api获得报价
结果:什么都没发生
附加:如果有效,我如何添加代码以使其获得随机引用?
答案 0 :(得分:2)
我使用jsonp及其回调,在API网站的manual之后开始工作。
我甚至做得更漂亮:D
var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en';
$(document).ready(function() {
$("#btn").click(function() {
$.ajax({
url:quoteUrl ,
crossDomain: true,
jsonpCallback: 'parseQuote',
dataType: 'jsonp',
success:function(data){
$("#insertionPoint>#quote").html(data.quoteText);
$("#insertionPoint>#author").html(data.quoteAuthor);
}
});
});
});
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<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" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<h1>Random quote Machine</h1>
<blockquote id="insertionPoint">
<span id="quote">Quotes come here</span>
<footer id="author">Author comes here</footer>
</blockquote>
<button class="btn btn-info" id="btn">Next Quote</button>
&#13;
您应该更改#insertionPoint
的html而不是替换它,否则该功能将无法继续工作,因为此元素将不再存在。
答案 1 :(得分:1)
替换
$insertion.replaceWith('<p>'+quote+'</p>');
带
$insertion.html('<p>' + quote + '</p>');