点击按钮触发Axios请求后如何在新标签页渲染自定义HTML内容
实现方法
你直接把newWin.document.write()的入参替换为你自定义的完整HTML字符串即可,还可以将接口返回的res.data动态嵌入到HTML的指定位置,示例代码如下:
click() { this.setState({ isLoading: true }); axios .get(`http://localhost:5000/model-list`) .then((res) => { this.setState({ inferenceout: res.data, isLoading: false, }) const newWin = window.open("about:blank", "resultPage", "width=800,height=600"); // 自定义HTML内容,可根据需求修改样式、结构、引入脚本 const customHtml = ` <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>接口返回结果</title> <style> * { margin: 20px; } pre { background: #f5f5f5; padding: 15px; border-radius: 8px; overflow-x: auto; } h1 { color: #333; } </style> </head> <body> <h1>模型列表查询结果</h1> <pre>${JSON.stringify(res.data, null, 2)}</pre> <!-- 你可以在这里插入任意自定义的HTML标签、脚本逻辑 --> <script> // 自定义脚本逻辑示例 console.log('新页面加载完成,接口返回数据:', ${JSON.stringify(res.data)}) <\/script> </body> </html> ` newWin.document.write(customHtml) // 写入完成后调用close结束文档流,避免浏览器加载状态卡住 newWin.document.close() }) }
注意事项
- 可以根据需求任意修改
customHtml里的结构、样式、脚本逻辑,要插入动态内容直接用模板字符串的${}语法嵌入即可 - 模板字符串里的内嵌
<script>标签的结束标识建议转义为<\/script>,避免被识别为外层脚本的结束标签导致报错 - 如果需要插入的HTML内容很长,建议单独封装为一个函数返回HTML字符串,避免代码冗余
内容的提问来源于stack exchange,提问作者Karthikeyan M
相关产品推荐
相关产品推荐

