【发布时间】:2016-03-14 19:05:36
【问题描述】:
我今天发生了一件奇怪的事情:我试图使用 jquery 和 ajax 从 JSON 文件中检索一些数据,并将这些数据显示在网页上。我在 Internet 上找到的这个示例在基本操作系统上为我工作。当我尝试从具有 Win10 操作系统的虚拟机运行它时,它不起作用,这意味着它会将我扔到:alert('There was a problem with the server. Try again soon!');。为什么?
非常感谢!
这是在我的 data19.json 文件中:
{
"one": "Learned Optimism",
"two": "Deliberate Practice",
"three": "Getting Things Done"
}
我的脚本 script19.js 是:
$(function() {
$('#clickme').click(function() {
$.ajax({
url: 'data19.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'interest-list',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('There was a problem with the server. Try again soon!');
}
}
});
});
});
我的 HTML 文件是:
<!DOCTYPE html>
<html>
<head>
<title>19. Using jQuery to retrieve JSON via AJAX</title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="script19.js"></script>
</head>
<body>
<h1 id="title">19. Using jQuery to retrieve JSON via AJAX</h1>
<a href="#" id="clickme">Get JSON Data</a>
</body>
</html>
【问题讨论】:
-
你无法从本地文件中检索json,所以你应该设置一个服务器,比如:localhost:8080/C9HS_19.html