此代码在HTML模拟器中运行,但在复制并粘贴它并尝试在浏览器中运行时不起作用。
为什么会这样? 我的浏览器是否提供某种保护措施?我如何修改代码以使其在浏览器中工作?
源:https://www.quackit.com/json/tutorial/json_with_http_jquery.cfm
此处复制代码:
<!doctype html>
<title>Example</title>
<!-- Load JQuery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<!-- Load JSON file and output it-->
<script>
$(function() {
// User clicks the "getData" button
$("#getData").click(function() {
// Put artistList element and JSON file location into a variable
var artistList = $("#artistList");
var url = "https://www.quackit.com/json/tutorial/artists.txt";
// Get the JSON file
$.getJSON(url, function(data) {
// Put artist info into a variable
var artists = data.artists.map(function(item) {
return item.artistname + " (" + item.born + ")";
});
// Remove all child nodes (including text nodes)
artistList.empty();
// Format artists with HTML tags
if (artists.length) {
var content = "<li>" + artists.join("</li><li>") + "</li>";
var list = $("<ul>").html(content);
artistList.append(list);
}
});
});
});
</script>
<!-- The output appears here -->
<button id="getData">Display Artists</button>
<div id="artistList"></div>
答案 0 :(得分:0)
当您尝试使用文件协议在本地运行此html时,您遇到两个问题:
首先,您必须在开头添加 http:更改脚本的 src 。
其次,代码中对外部api的请求将是跨域请求,并且默认情况下被浏览器阻止。 在Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?
中了解更多相关信息