我正在开发一个html / js项目,它从https://quotesondesign.com/the-api/ API中检索JSON对象。当我使用Atom html预览器时,以下代码工作正常,但是,当我尝试使用Firefox或Chrome打开它时,JS无法正常运行。报价和作者都没有被检索。这是FreeCodeCamp项目的一部分。
这是JS,CSS和HTML代码:
$(document).ready(function() {
let quote;
let author;
getQuote();
function getQuote() {
$.ajaxSetup({ cache: false });
$.ajax({
type: 'GET',
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
success: function(data){
quote = data[0].content;
author = data[0].title;
$("#text").html(quote);
$("#author").html('-' + author);
}
});
/*$.ajaxSetup({ cache: false });
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1", function(a) {
quote = a[0].content;
author = a[0].title;
$("#text").html(quote);
$("#author").html('-' + author);
});*/
};
$("#new-quote").on("click", function(){
getQuote();
});
$("#tweet-quote").on("click", function() {
window.open("twitter.com/intent/tweet?text=" + quote + " -" + author);
});
});
body {
background-color: black;
color: white;
}
#quote-box {
border: 2px solid white;
padding: 20px;
color: white;
max-width: 500px;
height: auto;
margin: auto;
}
button {
margin: 20px;
border-radius: 5%;
border: 2px solid white;
background-color: black;
color: white;
}
span {
width: auto;
height: auto;
}
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="qm.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
<script src="file:///Users/RoseSamuel/Desktop/QuoteMachine/qm.js" type="text/javascript"></script>
</head>
<body>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<h1 class="text-center">Quote Machine</h1>
<div id="quote-box" class="text-center">
<span id="text"></span> <br>
<span id ="author"></span> <br>
<button id="new-quote" >New Quote</button>
<button id="tweet-quote">Tweet Quote</button>
</div>
</body>
</html>
可能是Atom Html预览器只是为了了解Html的外观并且不包括所有浏览器功能。拒绝跨资源访问资源是您的Internet浏览器强加的限制。服务器告诉您的浏览器您的脚本正在尝试从其他域检索资源,而它是阻止访问的浏览器。这种限制既不存在,也不存在。如果您开发Powershell脚本或C#控制台应用程序,因为它们在Windows上运行,而您的Javascript代码使用浏览器作为平台,因此受其限制。