鍍金池/ 問答/網(wǎng)絡安全  HTML/ js 讀取本地文件

js 讀取本地文件

需求是這樣的,我有一個 index.html 里面有個 div#demo,對應有一個 index.js 文件。另外還有一個 temp.html,我想在 index.js 里讀取 temp.html 的某一段內容插入到 div#demo 里面去。
這幾個文件都是在客戶端的,temp.html 文件里有個 template 標簽,因為這個標簽里的內容我不能直接放到 index.html 里面去,所以想通過 index.js 把他讀取出來在放到 div#demo 里。

// index.html
<body>
<div id="demo"></div>
</body>

// temp.js
<template>
<div>一些內容</div>
</template>

// index.js
讀取 temp.js 并插入到 div#demo 中
回答
編輯回答
臭榴蓮

js 在瀏覽器環(huán)境下并沒有讀寫文件的相關能力,一般是通過 XHR 將服務器端文件作為網(wǎng)絡資源給 js 使用。

2018年3月17日 01:22
編輯回答
萢萢糖

題目有歧義,看題主的描述,應該是想通過前端的js讀取 “服務端” 的另一個文件中的部分內容。

我想到兩種方法:

  1. 后端寫個接口,去讀取你想讀取的文件中的內容,index.html去請求后端,后端去讀temp.html中你想要的內容;

2.第二種方法是純前端的實現(xiàn), index.html把需要內容的標志存到sessionStorage或localStorage中,temp.html監(jiān)聽storage事件,讀取Storage中的標志,讀取temp.html中的內容并存入Storage中,index.html監(jiān)聽storage事件,讀取需要的內容。
這種方法,當然也可以叫做“讀取本地文件”.....

2018年7月22日 11:16