React项目如何将axios响应结果在新窗口打开或导出为JSON文件
可行实现方案
以下两种方案都不需要修改现有代码的其他逻辑,只需替换handleSubmit方法中axios请求成功后的逻辑即可:
方案1:将返回结果导出为本地JSON文件
通过浏览器内置的Blob API生成JSON文件,触发浏览器自动下载:
handleSubmit(event) { event.preventDefault(); axios.post('http://localhost:5000/getmodell', { model: this.state.model, dataset:this.state.course }) .then((res) => { console.log(res.data); // 新增导出逻辑 const jsonContent = JSON.stringify(res.data, null, 2); const blob = new Blob([jsonContent], { type: 'application/json' }); const downloadUrl = URL.createObjectURL(blob); const tempLink = document.createElement('a'); tempLink.href = downloadUrl; // 自定义导出文件名,可根据需求调整命名规则 tempLink.download = `${this.state.model}_${this.state.course}_查询结果.json`; document.body.appendChild(tempLink); tempLink.click(); // 清理临时元素 document.body.removeChild(tempLink); URL.revokeObjectURL(downloadUrl); }); }
方案2:在新页面中展示返回结果
打开空白标签页直接渲染格式化后的JSON数据:
handleSubmit(event) { event.preventDefault(); axios.post('http://localhost:5000/getmodell', { model: this.state.model, dataset:this.state.course }) .then((res) => { console.log(res.data); // 新增新页面展示逻辑 const formattedJson = JSON.stringify(res.data, null, 2); const newWindow = window.open('', '_blank'); newWindow.document.write(` <html> <head><title>查询结果</title></head> <body> <pre style="padding: 20px; background: #f6f8fa; border-radius: 6px; line-height: 1.5;"> ${formattedJson} </pre> </body> </html> `); newWindow.document.close(); }); }
如果需要同时支持两种操作,可以在页面上新增两个按钮,分别绑定对应逻辑即可,现有查询逻辑不需要做任何调整。
内容的提问来源于stack exchange,提问作者Karthikeyan M
相关产品推荐
相关产品推荐

