日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Vue 正文

vue?如何打開接口返回的HTML文件_vue.js

作者:wuyuezhaolu ? 更新時間: 2022-04-03 Vue

前言:接口測試平臺,后端使用django,前端使用vue+element。項目接口平臺測試完成,需要把后臺產生的測試報告返回給前端展示。

一、后端接口

????1、配置下django的template的參數,templates文件夾是放在project的目錄下面的,是項目中或者說項目中所有的應用公用的一些模板

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'userfiles')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

2、視圖函數,讀取template目錄下report文件夾的報告,并返回給前端

 def getReport(self, request):
        # 獲取POST BODY信息
        reportId = request.data["id"]
        try:
            print(os.getcwd()) # 打印程序運行目錄
            template = loader.get_template(f"./report/{reportId}.html")
            # template = loader.get_template(f"1.html")
            return Response(template.render())
            # return HttpResponse(template.render())
        except Exception as e:
            content = {'message': '獲取報告失敗'}
            return Response(content)

二、前端

1、如果后端返回的HTML文件不包含js文件,可以使用vue的v-html,vue的v-html只能渲染html元素和css文件,,不能執行js文件

2、后端返回的數據,HTML文件包含js文件。使用下面這種方法,接口獲取到的html數據在暫存的本地localStorage,再讀取數據,然后在新窗口打開報告。

接口返回的數據如下:

?template:

 <el-button type="warning" @click="viewReport" :disabled="reportDisabled

methods:

 
 // 查看測試報告
  viewReport () {
    var message = {id:1}
    //  axios 通過接口獲取后臺的報html告文件數據
    getReport(message).then(res => {
      this.$message({
        showClose: true,
        message: res.data.message,
        type: 'success'
      })
      // res.data 為接口返回的html完整文件代碼
       // 必須要存進localstorage,否則會報錯,顯示不完全
      window.localStorage.removeItem('callbackHTML')
      window.localStorage.setItem('callbackHTML', res.data)
    // 讀取本地保存的html數據,使用新窗口打開
      var newWin = window.open('', '_blank')
      newWin.document.write(localStorage.getItem('callbackHTML'))
      // 關閉輸出流
      newWin.document.close()
    }).catch(err => {
      this.$message({
        showClose: true,
        message: err.response.msg,
        type: 'error'
      })
    })
  }

至此結束,點擊下按鈕即可在新窗口展示測試報告了

原文鏈接:https://blog.csdn.net/wuyuezhaolu/article/details/120452840

欄目分類
最近更新