tic*_*tas 5 javascript xml ajax jquery cors
我正在尝试通过嵌入式表单将表单数据发送给Google。
我发现这篇文章似乎可以回答我的问题,但出现CORS错误。有办法解决吗?
其他帖子似乎说,CORS不是问题,但我遇到了错误。
这是我的代码:
-JS-
function ajax_post() {
var field1 = $('#email').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/xxxxxxxxxxxxxxxxxxxxxx/formResponse",
data: {"entry.xxxxxxxxxx": field1},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
-HTML-
<form id="emailForm" target="_self" onsubmit="" action="javascript: ajax_post()">
<input id="email" type="text" autocomplete="off" tabindex="0" name="entry.xxxxxxxxxx" required>
<button id="send" type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
\ xe2\x80\x9cNo 'Access-Control-Allow-Origin' header is present on the requested resources\xe2\x80\x9d 消息表明来自https://docs.google.com/forms/d/e/xxxx/formResponseURL 的响应当前不包含Access-Control-Allow-Origin响应标头,因此浏览器won\xe2\x80\x99t 不允许您的前端 JavaScript 代码访问响应。
鉴于此,从您的前端代码中,您无法判断请求是否POST成功。但除非出现任何其他问题,该请求似乎总是会成功。如果请求根本没有到达服务器(由于某些网络错误),那么您将遇到不同的故障情况,该故障情况可以从前端代码中观察到,因此您可以实际捕获它。
因此,您知道请求已成功到达服务器的方法就是您不会从前端代码中观察到任何其他失败。
\n小智 5
我发现,使用隐藏的 iframe 作为目标来发布表单,并在提交响应时捕获 iframe 重新加载实际上更容易。
例如,如果这是您的表格:
<form id="my-form" target="my-response-iframe" action="https://docs.google.com/forms/u/1/d/e/<YOUR-ID>/formResponse" method="post">
<input type="text" name="entry.12345678" value="" required>
<input type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)
然后在同一页面上包含一个 iframe,其 id 和名称与您在表单中作为目标输入的名称相同:
<iframe id="my-response-iframe" name="my-response-iframe"></iframe>
Run Code Online (Sandbox Code Playgroud)
提交表单后,它应该重新加载该 iframe,并显示“您的回复已被记录”。来自谷歌的页面。我们可以使用 JavaScript 捕获重新加载,因此请在表单和 iframe 之后包含此内容:
<script type="text/javascript">
// set the target on the form to point to a hidden iframe
// some browsers need the target set via JavaScript, no idea why...
document.getElementById('my-form').target = 'my-response-iframe';
// detect when the iframe reloads
var iframe = document.getElementById('my-response-iframe');
if (iframe) {
iframe.onload = function () {
// now you can do stuff, such as displaying a message or redirecting to a new page.
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
您无法检查响应是否已正确提交,因为您无法检查跨源 iframe 的内容(这将是一个巨大的安全风险),因此只需假设如果此 iframe 重新加载,则响应正常。
您可以使用以下 CSS 隐藏 iframe:
visibility: hidden
height: 1px;
Run Code Online (Sandbox Code Playgroud)
如果你问我的话,就干净多了,没有控制台错误或失败的请求。