向Salesforce提交表单后如何实现页面重定向?
我在向Salesforce服务器提交表单时,希望提交完成后跳转到「感谢您,我们将联系您」的页面,但始终无法实现。我尝试了两种方案,均存在问题:
方案1:HTML+原生JS
HTML代码:
<form action="https://webto.salesforce.com/..." method="POST" class="row" id="form"> <input class="btn btn-dark" type="submit" name="submit" onsubmit="Example()"> </form>
JS代码:
function Example() { setTimeout(function () { window.location = "http://myWeb.com/Thanks" }, 1); };
问题:表单能成功提交,但不会跳转到目标页面。
方案2:使用Fetch API
代码:
document.addEventListener('DOMContentLoaded', function () { var form = document.getElementById('form'); console.log(form); formulario.addEventListener("submit", handleSubmit); async function handleSubmit(event) { event.preventDefault(); const form = new FormData(this); response = fetch(this.action, { method: this.method, body: form, headers: { 'Accept': "application/x-www-form-urlencoded", 'Access-Control-Allow-Origin': 'http://myWeb.com/' } }); if (response.ok) { this.reset(); window.location.href = 'http://myWeb.com/Thanks' } } });
问题:出现CORS跨域错误,错误信息如下:
Access to fetch at 'https://SalesForceWeb.com' from origin 'http://MyWeb:1111' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
另外,我是从http://MyWeb:1111/Home/Index发送数据的,这会不会导致问题?我尝试设置'Access-Control-Allow-Origin': 'http://myWeb.com:1111/Home/Index',但请求似乎是从http://myWeb.com:1111/发起的。
方案1修复:绑定正确的事件并处理默认行为
方案1的核心问题是onsubmit事件绑定错误——按钮没有onsubmit事件,该事件应该绑定在<form>标签上。同时需要阻止表单默认提交行为,避免页面刷新覆盖跳转逻辑:
<form action="https://webto.salesforce.com/..." method="POST" class="row" id="form" onsubmit="Example(event)"> <input class="btn btn-dark" type="submit" name="submit"> </form>
function Example(event) { // 阻止表单默认提交刷新页面 event.preventDefault(); const form = document.getElementById('form'); // 手动提交表单 form.submit(); // 延迟跳转,确保表单提交完成 setTimeout(() => { window.location = "http://myWeb.com/Thanks"; }, 500); };
方案2修复:解决CORS跨域问题
CORS错误的本质是:Access-Control-Allow-Origin是服务器返回的响应头,不是前端请求头,你在fetch里设置这个请求头完全无效。Salesforce Web-to-Lead接口本身不支持前端跨域请求,有两种解决方式:
- 方式1:使用
no-cors模式
该模式下浏览器不做CORS校验,但无法获取响应状态,只能在请求发送后直接跳转:document.addEventListener('DOMContentLoaded', function () { var form = document.getElementById('form'); // 修正变量名错误:formulario改为form form.addEventListener("submit", handleSubmit); async function handleSubmit(event) { event.preventDefault(); const formData = new FormData(this); await fetch(this.action, { method: this.method, body: formData, mode: 'no-cors' }); window.location.href = 'http://myWeb.com/Thanks'; this.reset(); } }); - 方式2:后端代理请求
在你的后端服务(如http://myWeb.com)开发一个中转接口,前端将表单数据提交到该接口,再由后端转发至Salesforce接口。后端请求不受浏览器CORS限制,还能验证提交结果。
关于请求来源的疑问
浏览器同源策略中,来源指协议+域名+端口,与路径无关。不管你从http://MyWeb:1111/Home/Index还是http://MyWeb:1111/发起请求,来源都是http://MyWeb:1111。但再次强调:Access-Control-Allow-Origin是服务器响应头,前端设置请求头无效。
内容的提问来源于stack exchange,提问作者Bilbit Bolson

