我正在尝试使用api中的JSON生成随机引号。点击按钮,json应填充代替"消息将在此处"。但我发现卡住了。代码如下:项目链接:
https://codepen.io/monsieurshiva/pen/awBbEE
<html>
<head>
<script>
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en", function(json) {
$(".message").html(JSON.stringify(json));
});
});
});
</script>
</head>
<body>
<div class = "col-xs-12 well message">
The message will go here
</div>
<button id = "getMessage" class = "btn btn-primary">
Get Message
</button>
</body>
</html>
答案 0 :(得分:1)
请尝试使用它为我工作,没有跨域错误。我已将其更改为函数并使用ajax获取数据。还可以使用https
api URL来避免不安全的脚本错误。
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$( function() {
$('#getMessage').on( 'click', function(){
load();
} );
});
var linkUrl = "https://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en";
var load = function() {
$.ajax(
{
dataType : "jsonp",
jsonp : "jsonp",
url : linkUrl,
success : function(response){
$(".message").html(response.quoteText);
}
});
};
});
</script>
</head>
<body>
<div class = "col-xs-12 well message">
The message will go here
</div>
<button id = "getMessage" class = "btn btn-primary">
Get Message
</button>
</body>
</html>
&#13;
答案 1 :(得分:0)
尝试使用JSONP - 示例
$(document).ready(function(){
$.ajax({
url: 'http://openexchangerates.org/latest.json',
dataType: 'jsonp',
success: function(json) {
// Rates are in `json.rates`
// Base currency (USD) is `json.base`
// UNIX Timestamp when rates were collected is in `json.timestamp`
rates = json.rates;
base = json.base;
console.log(rates);
}
});
});
或者这个
<script>
(function() {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON( flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function( data ) {
$.each( data.items, function( i, item ) {
$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
if ( i === 3 ) {
return false;
}
});
});
})();
</script>