我想用纯 JS 发送 AJAX 请求,而不使用服务器或闲置 Chrome 浏览器中的安全性。
这是我的代码:
if(document.getElementById("showJson")){
document.getElementById("showJson").addEventListener("click", init);
}
function init(){
loadJSON(function (response){
var actual_JSON = JSON.parse(response);
});
}
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
console.log(xobj);
}
这是 JSON 文件“students”:
[{
"name" : "Mohamed Kamel",
"age" : 24,
"grade" : 100
},{
"name": "hamada",
"age" : 20,
"grade":90
},{
"name" : "ali",
"age" : 23,
"grade" : 80
}]
最佳答案
你不能。
出于安全原因,下载文件必须仅在用户许可的情况下进行。
但是你为什么要这样做呢?服务器读取文件并发送内容或发送文件没有(性能)差异。服务器以这两种方式读取文件。
关于javascript - 使用纯javascript发送Ajax请求从json文件中获取json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42449081/