此代码在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>
尝试使用文件协议本地运行此HTML时,您有两个问题:
首先,您必须更改脚本的添加 http:的开始。
第二,您代码中对外部API的请求将是跨域请求,并且默认情况被浏览器阻止。了解有关为什么我的JavaScript获得"不访问控制"标题的信息的更多信息。邮递员不这样的错误?