简体   繁体   English

如何将后请求的响应放入新窗口/选项卡

[英]How to put the response of a post-request into a new window/tab

I have this working example of how to use POST and put the server-generated html in a new window:我有这个关于如何使用 POST 并将服务器生成的 html 放入新的 window 的工作示例:

const response = await this.axiosInstance.post(url, postData)
const htmlResponse = response.data
const newWindow = window.open()
newWindow.document.write(htmlResponse)

However I'm not sure if this is the best or even correct way to do it.但是我不确定这是否是最好的甚至是正确的方法。 I see a few warnings with this.我看到了一些警告。 I get a warning on the last line that newWindow is possibly ' null '.我在最后一行收到警告说newWindow可能是' null '。 If switching to TypeScript I am also not sure the type of htmlResponse .如果切换到 TypeScript 我也不确定htmlResponse的类型。 I would assume Document , but write() only supports string , so it might be the correct classification.我会假设Document ,但 write() 只支持string ,所以它可能是正确的分类。

Is there a better way to put the content of a post-request into a new window?有没有更好的方法将后请求的内容放入新的 window 中?

Update: The content-type is of type text/html;更新:内容类型为text/html 类型; charset=UTF-8 , not sure if it changes anything. charset=UTF-8 ,不确定它是否会改变任何东西。

What you have there might be enough for your use case.您所拥有的可能足以满足您的用例。 One might recommend waiting for some form of a ready event before manipulating the DOM.有人可能会建议在操作 DOM 之前等待某种形式的就绪事件。

const newWindow = window.open();
newWindow.onload = (event, f, g, h) => newWindow.document.write('Do great things.');

A much better solution might be fetching actual data instead of an HTML string from the server, creating a template page to receive the data, and rendering a well-formatted page.更好的解决方案可能是从服务器获取实际数据而不是 HTML 字符串,创建模板页面来接收数据,并呈现格式良好的页面。

The Window.postMessage() API could be used to send data between parent and child windows. Window.postMessage() API可用于在父子 windows 之间发送数据。 This is especially useful if you need to circumvent the Same-origin policy .如果您需要规避Same-origin policy ,这将特别有用。

I have made several assumptions, and this suggestion might not work for your use case.我做了几个假设,这个建议可能不适用于您的用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM