前端 readFileContent XMLHttpRequest + Promise讀取文件內容 - 戴向天

大家好!我叫戴向天

QQ羣:602504799

QQ:809002582

function readFileContent(path = null) {

  if (!path) return false

  return new Promise(function (resolve, reject) {
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {

      if (xhr.readyState == 4 && xhr.status == 200) resolve(xhr.responseText)

    }

    xhr.onerror = (e) => {
      resolve(e)
    }

    xhr.open("get", path, true)

    xhr.send(null)

  })

}

使用方法

 let context = await this.readFileContent("/index.html");

  console.log(context)

效果圖
在這裏插入圖片描述在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章