如何使用Jquery和Ajax从JSON文件中检索数据? [英] How to retrieve data from JSON file using Jquery and ajax?
问题描述
今天发生了一件奇怪的事情:我试图使用jquery和ajax从JSON文件中检索一些数据,并将这些数据显示在网页上.我在Internet上找到的该示例在基本OS上为我工作.当我尝试从装有Win10 OS的虚拟机上运行它时,它不起作用,这意味着它使我无法执行以下操作:alert('There was a problem with the server. Try again soon!');
.为什么?
提前非常感谢!
A weird thing happened to me today: I was trying to retrieve some data from a JSON file using jquery and ajax, and display this data on a webpage. This example, which I found on the Internet, worked for me on the base OS. When I try run it from a virtual machine with Win10 OS it doesn't work, meaning that it throws me to: alert('There was a problem with the server. Try again soon!');
. Why?
Many thanks in advance!
这在我的data19.json文件中:
This is in my data19.json file:
{
"one": "Learned Optimism",
"two": "Deliberate Practice",
"three": "Getting Things Done"
}
我的脚本script19.js是:
My script, script19.js, is:
$(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数据"时,这就是控制台中显示的内容:
Also when I click "Get JSON Data" this is what appears in Console:
推荐答案
您的代码是corect,您必须将代码移动到服务器,在服务器上,您的ajax调用json,都可以使用.
your code is corect, you must move your code to server, on server your ajax call json, all will be work.
这篇关于如何使用Jquery和Ajax从JSON文件中检索数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!