我想制作一个带有 3 个复选框的表单,这些复选框都有值。当表单被提交并且浏览器离线时。当浏览器/设备联机时,必须发送表单数据。
如果您依赖 HTTPS,您可以使用Service Worker API,
或者您可以检查navigator.onLine
navigator.onLine
和online
事件提交表单数据stack
数组。online
事件和FIFO -empty的stack
阵列,提交对象一个接一个。 // App's stack to store form data - while offline
const stack = []; // Make available throughout your APP. Or use sessionStorage
// SUBMIT
function submit(formData) {
console.log(formData); // TODO: send to server using jQuery $.ajax or whatever
}
// PRE SUBMIT
function preSubmit(ev) {
ev.preventDefault(); // Prevent form submit, we'll use AJAX
const formData = { // or use JS's FormData API instead
action: this.action, method: this.method, data: $(this).serialize()
};
if (navigator.onLine) {
submit( formData ); // Submit with AJAX, as usual
} else {
stack.push( formData ); // Push to stack! We're offline!
}
}
// CHECK - Called when online
function stackCheck() {
if (stack.length) {
// Empty + submit the data in stack, one by one
while (stack.length) submit( stack.shift() );
}
}
// Listen for when online
window.addEventListener('online', stackCheck);
// Every form on our page
$('form').on('submit', preSubmit);
<form action="/api/message" method="delete">
<input type="hidden" name="id" value="31">
<input type="submit" value="Delete message">
</form>
<form action="/api/user" method="post">
<input type="text" name="name" value="john">
<input type="text" name="surname" value="doe">
<input type="submit" value="Add user">
</form>
Now, open developer console and check the "Offline" mode.<br>
Click the buttons and turn back online.
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
PS:值得阅读和实施:https : //developer.mozilla.org/en-US/docs/Web/API/FormData
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句