Eli*_*res 5 javascript forms events
我有这个简单的形式:
<form action="www.faildomain.com">
<input name="foo" value="bar">
<button type="submit">Submit</button>
</form>
Run Code Online (Sandbox Code Playgroud)
就我而言,该操作将失败。但这是否可能是有效的操作,但是用户遇到了连接错误?
是否生成了其他Javascript事件,或者这超出了我的控制范围?
如果您不处理提交事件,这将超出您的控制。基本上,当您单击提交按钮时,您的浏览器将对您的“操作”URL 执行 HTTP POST 请求。
如果您想在发送之前检查输入的有效性,您需要做的是处理表单提交事件:submit。
var myForm = document.getElementById('my-form');
// Add a listener to the submit event
myForm.addEventListener('submit', function (e) {
var errors = [];
// Check inputs...
if(errors.length) {
e.preventDefault(); // The browser will not make the HTTP POST request
return;
}
});
Run Code Online (Sandbox Code Playgroud)
但是,即使使用此代码,您也永远不会知道用户是否有网络问题。
检查此类错误的唯一方法是使用 Ajax 对后端路由进行异步调用(它只是一个 HTTP POST 请求,异步调用)。例如,使用 jQuery:
$("#myForm").on("submit", function(e) {
event.preventDefault();
var data = {};
// Get data from form...
// Stop form from submitting normally
$.post("www.faildomain.com", data)
.done(function(data) {
// No problem
},
.fail(function (jqXHR, textStatus) {
// An error occured (the server responded with an error status, network issue, ...)
// More information about the error can be found in jqXHR and textStatus
},
.always(function () {
// This method is always executed whether there were an error or not
});
Run Code Online (Sandbox Code Playgroud)