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

js 讀取本地文件

需求是這樣的,我有一個(gè) index.html 里面有個(gè) div#demo,對(duì)應(yīng)有一個(gè) index.js 文件。另外還有一個(gè) temp.html,我想在 index.js 里讀取 temp.html 的某一段內(nèi)容插入到 div#demo 里面去。
這幾個(gè)文件都是在客戶(hù)端的,temp.html 文件里有個(gè) template 標(biāo)簽,因?yàn)檫@個(gè)標(biāo)簽里的內(nèi)容我不能直接放到 index.html 里面去,所以想通過(guò) index.js 把他讀取出來(lái)在放到 div#demo 里。

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

// temp.js
<template>
<div>一些內(nèi)容</div>
</template>

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

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

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

題目有歧義,看題主的描述,應(yīng)該是想通過(guò)前端的js讀取 “服務(wù)端” 的另一個(gè)文件中的部分內(nèi)容。

我想到兩種方法:

  1. 后端寫(xiě)個(gè)接口,去讀取你想讀取的文件中的內(nèi)容,index.html去請(qǐng)求后端,后端去讀temp.html中你想要的內(nèi)容;

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

2018年7月22日 11:16