如何将 .json 文件设置为在 window.open (javascript) 中使用的变量?
How To Set a .json file as a variable for use in window.open (javascript)?
我使用 html 和 javascript 制作了一个网站。我在这两个方面都很有经验,但我正在努力制作一个按钮打开一个网站,其中 url 来自 json 文件。所以我想将一个 json 文件作为一个变量,然后将它与 window.open(JSON-url,"_blank") 一起使用。然后我想创建一个名为 JSON-url 的 var,它必须与 .json 文件链接。
我搜索了很多例子,但似乎无法找到正确的措辞。我尝试过 w3schools、Stack Overflow、Quora 和许多其他网站。我主要尝试了其他搜索,例如 "How To Make JSON a variable to use in window.open javascript",但也没有用。
{
"JSON-url": "https://www.google.com"
}
我敢打赌,有很多人知道这个问题的答案,所以请提出您的想法!
在 window.open()
中为 URL 使用变量时,JSON 文件没有什么特别之处。你做的和其他的一样URL.
使用FileReader
API读取文件,然后使用URL打开文件内容
function openFile(files) {
if (files.length == 0) {
return;
}
const reader = new FileReader();
reader.onload = function() {
var url = reader.result.trim(); // Contents of the file
console.log("Opening " + url);
window.open(url, "_blank");
}
reader.readAsText(files[0]);
}
Select file:
<input type="file" id="txt" accept="text/plain" onchange="openFile(this.files)">
这在上面的代码片段中不起作用,因为堆栈代码片段是沙盒的,不允许 window.open()
。
我使用 html 和 javascript 制作了一个网站。我在这两个方面都很有经验,但我正在努力制作一个按钮打开一个网站,其中 url 来自 json 文件。所以我想将一个 json 文件作为一个变量,然后将它与 window.open(JSON-url,"_blank") 一起使用。然后我想创建一个名为 JSON-url 的 var,它必须与 .json 文件链接。
我搜索了很多例子,但似乎无法找到正确的措辞。我尝试过 w3schools、Stack Overflow、Quora 和许多其他网站。我主要尝试了其他搜索,例如 "How To Make JSON a variable to use in window.open javascript",但也没有用。
{
"JSON-url": "https://www.google.com"
}
我敢打赌,有很多人知道这个问题的答案,所以请提出您的想法!
在 window.open()
中为 URL 使用变量时,JSON 文件没有什么特别之处。你做的和其他的一样URL.
使用FileReader
API读取文件,然后使用URL打开文件内容
function openFile(files) {
if (files.length == 0) {
return;
}
const reader = new FileReader();
reader.onload = function() {
var url = reader.result.trim(); // Contents of the file
console.log("Opening " + url);
window.open(url, "_blank");
}
reader.readAsText(files[0]);
}
Select file:
<input type="file" id="txt" accept="text/plain" onchange="openFile(this.files)">
这在上面的代码片段中不起作用,因为堆栈代码片段是沙盒的,不允许 window.open()
。