[英]Fetch json data from local using pure Javascript Ajax
So I know this is so lame to ask this question as I have spent a day searching on this subject without any success. 所以我知道问这个问题真是me脚,因为我花了一天的时间在这个问题上进行搜索,但没有成功。 As many others, I'm facing the crossdomain problem. 与其他许多人一样,我也面临着跨域问题。 The suggestion I see everywhere is to update the JSON file on a server or use localhost which I can't use because my assignment is not allowed to do so. 我到处都看到的建议是更新服务器上的JSON文件或使用无法使用的本地主机,因为我的分配不允许这样做。
I am posting this question hoping there is some other solution for this. 我发布此问题,希望对此有其他解决方案。 I need to fetch data from a JSON file locally using pure JavasSript and Ajax which does not involve hosting on a server nor localhost (using absolute path is also a bad idea). 我需要使用纯JavasSript和Ajax从本地从JSON文件中获取数据,这不涉及在服务器或本地主机上托管(使用绝对路径也是一个坏主意)。
This is my code so far: 到目前为止,这是我的代码:
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', '/json/userinfo.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
(function() {
loadJSON(function(response){
var actual_JSON = JSON.parse(response);
console.log(actual_JSON);
})
})()
You won't be able to access local files using AJAX/XHR. 您将无法使用AJAX / XHR访问本地文件。 Its not designed for this purpose. 它不是为此目的而设计的。 What you can do is assign your json data into a variable in the json file, 您可以做的就是将json数据分配到json文件中的变量中,
var data = [{
}];
and then load your json file using script
tag like below: 然后使用如下script
标签加载json文件:
<script type="text/javascript" src="file_name.json"></script>
Now all the json data can be accessed using the data
variable. 现在可以使用data
变量访问所有json数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.