今天发生了一件奇怪的事情:我试图使用 jquery 和 ajax 从 JSON 文件中检索一些数据,并将这些数据显示在网页上。我在互联网上找到的这个示例在基本操作系统上对我有用。当我尝试从装有 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>
你的代码是正确的,你必须将你的代码移动到服务器,在服务器上你的ajax调用json,一切都会工作。
此场景请尝试使用 mozilla 浏览器。我在 chrome 中也遇到了同样的问题,但在 mozilla 上运行良好。 尝试为ajax请求添加值为“Get”的“type”参数。 参考这个 -
$.ajax({
type: "Get",
url: "data.json",
dataType: "json",
success: function(data) {
},
error: function(){
alert("json not found");
}
});
您提供的 json 数据(数据变量内部)不是数组,而是具有属性名称和值的单个对象。所以不要循环它们。相反,循环遍历这些属性并使用该属性访问值。
items=[];
for(r in data)
{
var key =r;
var val=data[r];
items.push('<li id="' + key + '">' + val + '</li>');
}
console.log(items);
工作示例这里
您可以检查您的 JSON 源是否需要互联网连接,如果是,那么您的虚拟机必须有互联网连接。
> Edit: Work around to read local JSON external file.
> 1. Create data.json file
> 2. Copy data into this file, for example:
> data = '[{"Id" : "1", "name" : "abc"},{"id" : "2", "name" : "xyz"}]';
> 3. Include path for this file as reference: <script type="text/javascript" src="data.json"></script>
> 4. Read JSON data by: var jsonData = JSON.parse(data);
我认为这可以解决问题。我自己试过了,可以用。
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to retrieve data from JSON file using Jquery and ajax?</title>
</head>
<body>
<div id="info"></div>
</body>
----------
<script type="text/javascript">
// script for Load 6 items at a time
var j=0; // index for start load in the object
var xdata; //A global variable for accessing it from inside the functions. it will load the file and do not want to read the file every time
//loading the JSON file to object by Ajax
var xreq = new XMLHttpRequest();
xreq.open('GET', 'file.json');
xreq.onload = function () {
//convert the file from text to object after opened it , on load the file
xdata = JSON.parse(xreq.responseText);
// call funcation to Build the page
addHtml(xdata, j);
// added 6 to the index for start loading from the next items
j = j + 6;
};
//send ajax
xreq.send();
// when the page is ready and already the scroll access to end page call the building function again
$(document).ready(function () {
$(window).scroll(function () {
// get the scroll Position
var scrollPosition = $(window).scrollTop();
// Multiplication operation in 1.2 in order to call the function before arrival the end of the page with 20%
if (scrollPosition >= $(document).height() - ($(window).height())*1.2 && j < xdata.length) {
addHtml(xdata, j);
j = j + 6;
xreq.send();
}
});
});
//funcation to Build the page
function addHtml(data,i) {
var info = document.getElementById("info");
var HtmlText ="";
// insert the HTML items before end a page
info.insertAdjacentHTML('beforeend',HtmlText);
}
</script>
----------
</html>
<!-- end snippet Alwahashi 2017 -->
您应该在 url 属性中为 Jquery 提供一个 URL。
仅将文件名解释为相对 HTTP url,操作系统可能会或可能不会为您返回此信息。
尝试将其编码为 FILE url,您可以通过直接在浏览器中打开 json 文件并从地址行复制 URL 来找到它。