[英]Using xhr2 with just javascript
I'm trying to use xhr2, to read through a json file.我正在尝试使用 xhr2 来读取 json 文件。 I've looked up numerous ways to achieve this but none seem to be working.
我已经查找了很多方法来实现这一点,但似乎都没有用。 The function below my require statements is the function that I see most often.
我的 require 语句下面的 function 是我最常看到的 function。 Ultimately what I wish to achieve is to make an array of objects by reading through multiple json files in order to fill a select order form on a website I am trying to create.
最终我希望实现的是通过读取多个 json 文件来制作对象数组,以便在我尝试创建的网站上填写 select 订单。
var http = require('http');
const ROOT = "./root_html";
var fs = require('fs');
var url = require('url');
var mime = require('mime');
//var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var XMLHttpRequest = require('xhr2');
var XMLHttpRequestUpload = XMLHttpRequest.XMLHttpRequestUpload;
//create the server
var server = http.createServer(handleRequest);
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("/civs/specials.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
I continue to get an error and am having an awfully hard time trying to find any information regarding why this error is occurring.我继续收到错误消息,并且很难找到有关此错误发生原因的任何信息。
C:\cygwin64\home\User\node_modules\xhr2\lib\xhr2.js:205
throw new NetworkError("Unsupported protocol " + this._url.protocol);
You may don't have a running server in your local computer.您的本地计算机中可能没有正在运行的服务器。 To run the server in the local computer:
要在本地计算机中运行服务器:
(1) Open Terminal (1) 打开终端
(2) cd <designated folder>
(2)
cd <designated folder>
(3) http-server
(3)
http-server
(4) Modify the file location related to the "designated folder" in JS file (4)修改JS文件中“指定文件夹”相关的文件位置
ex) "http://localhost:8080/<related folder>/<JSON file>"例如)“http://localhost:8080/<相关文件夹>/<JSON 文件>”
(5) Open another Terminal (5) 开启另一个Terminal
(6) node <JS file>
(6)
node <JS file>
npm i xmlhttprequest
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
It's work in my code它在我的代码中工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.