javascript - 提交到新 URL 后如何访问表单数据
问题描述
我想通过单击提交按钮将表单详细信息提交到一个全新的 URL。这是在 React 应用程序中。我通过以下方式对表单进行了基本设置。
let form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action",'localhost:3000/message/');
form.setAttribute("onSubmit", this.handleSubmit);
form.setAttribute("target", 'newWindow');
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "message");
hiddenField.setAttribute("value", "Hi. Im Awesome");
form.appendChild(hiddenField);
document.body.appendChild(form);
window.open('localhost:3000/message/', 'newWindow');
form.submit();
handleSubmit(e) {
e.preventDefault();
}
此时,当我提交时,会打开一个新选项卡,但该选项卡也会向表单数据localhost:3000/message
发出网络请求。localhost:3000/message/
我想停止额外的网络调用,localhost:3000/message/
并且我还希望能够直接在运行于 3000 的应用程序中访问表单数据。
这是可以实现的吗?
更新:正如@Jite 提到的, fetch 会清理这里的一些问题,所以我没有直接将数据作为表单发送,而是尝试通过 fetch api 发送它。
window.open('localhost:3000/message/', 'newWindow');
fetch('localhost:3000/message/', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: 'Hi, I'm even more awesome!'
})
})
运行的应用程序的渲染方法以localhost:3000\
以下方式设置 -
//import { BrowserRouter as Router, Route } from "react-router-dom";
render() {
return (
<Router>
<Route
path="/message"
render={props =>
<h2>Any message for me ?</h2>
}
/>
</Router>
);
}
我仍然不知道如何访问发送到此 url 的消息。
解决方案
我已经设法通过监听事件发送数据window.postMessage()
并在新窗口中访问它来解决这个问题。message
推荐阅读
- java - locationManager.getLastKnownLocation 在请求后返回 null
- c - 为什么我在 malloc 时遇到分段错误?
- batch-file - 如何创建文件夹并批量复制到其中
- image - 触发图像模态
- c++ - 我将如何优化此代码?
- jquery - 在数据表中显示空复选框而不是连字符
- android - Android toast 消息“后台更新服务正在运行(有意图)”
- jboss - 在 Wildfly-CLI 脚本中为 if/else 逻辑使用属性
- java - 问题测试 GCP 数据存储
- docker - Docker & gcplogs:消息为 json