如何使用 Jquery 和 ajax 从 JSON 文件中检索数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34179986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve data from JSON file using Jquery and ajax?
提问by Ionut
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!
今天发生了一件奇怪的事情:我试图使用 jquery 和 ajax 从 JSON 文件中检索一些数据,并将这些数据显示在网页上。我在 Internet 上找到的这个示例在基本操作系统上对我有用。当我尝试从带有 Win10 操作系统的虚拟机运行它时,它不起作用,这意味着它让我:alert('There was a problem with the server. Try again soon!');
. 为什么?提前谢谢了!
This is in my data19.json file:
这是在我的 data19.json 文件中:
{
"one": "Learned Optimism",
"two": "Deliberate Practice",
"three": "Getting Things Done"
}
My script, script19.js, is:
我的脚本 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!');
}
}
});
});
});
My HTML file is:
我的 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>
Also when I click "Get JSON Data" this is what appears in Console:
回答by Alex Repeckiy
your code is corect, you must move your code to server, on server your ajax call json, all will be work.
您的代码是正确的,您必须将代码移动到服务器,在服务器上您的 ajax 调用 json,一切都会正常工作。
回答by PrajaktaS
Please try using mozilla browser for this scenario. I have also faced the same issue in chrome but it works fine on mozilla. try adding "type" parameter with value "Get" for ajax request. Refer this one -
对于这种情况,请尝试使用 mozilla 浏览器。我在 chrome 中也遇到了同样的问题,但它在 mozilla 上运行良好。尝试为ajax请求添加值为“Get”的“type”参数。参考这个——
$.ajax({
type: "Get",
url: "data.json",
dataType: "json",
success: function(data) {
},
error: function(){
alert("json not found");
}
});
回答by Ovais Khatri
You may check if your JSON source requires internet connection, if YES then your VM must have internet connection working.
您可以检查您的 JSON 源是否需要 Internet 连接,如果是,则您的 VM 必须具有 Internet 连接工作。
> 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);
回答by Shyju
The json data you provided (inside data variable) is not an array, but a single object with property name and values. So don't loop through them. Instead loop through the properties of those and access the value using the property.
您提供的 json 数据(数据变量内部)不是数组,而是具有属性名称和值的单个对象。所以不要遍历它们。而是遍历这些属性并使用该属性访问值。
items=[];
for(r in data)
{
var key =r;
var val=data[r];
items.push('<li id="' + key + '">' + val + '</li>');
}
console.log(items);
Working sample here
工作样本在这里
回答by ???? ???????
I think this will solution the problem. I tried it by myself.u can use it.
我认为这将解决问题。我自己试过了。你可以用它。
<!-- 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 -->