我正在使用 XMLHttpRequest 读取名为“filename%3Fformat=json”的文件。我收到一条错误消息 zone.js:1382 GET http://localhost:3000/file%3Fformat=json 404(未找到)。
如果我将请求更改为“filename3Fformat=json”并将文件名更改为相同的(基本上从文件名和请求中删除%,它工作得很好......但我需要能够包含%在文件名中。
我在绝望中添加了setRequestHeader,但这似乎没有任何区别。
var requestAllStations = new XMLHttpRequest();
requestAllStations.onload = function ( ) {
if (requestAllStations.readyState == requestAllStations.DONE && requestAllStations.status == 200) {
// get json file content
var allFITStations = JSON.parse(requestAllStations.responseText);
console.log(allFITStations);
}
};
requestAllStations.open("get", "./file%3Fformat=json", true );
requestAllStations.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
requestAllStations.send();
最佳答案
使用Javascript的escape()函数对特殊字符进行编码。
requestAllStations.open("get", escape("./file%3Fformat=json"), true );
字符串转义字符串将如下所示:
./file%253Fformat%3Djson
关于javascript - 使用 XMLHttpRequest 读取文件名包含 % 的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035075/