验证表格前,我们提交 [英] Verify connection before form submit

查看:85
本文介绍了验证表格前,我们提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证表单之前,用户的互联网连接提交,让我的JavaScript验证功能可引发警报并返回false,如果没有任何联系。

I'm trying to verify the user's internet connection before form submit, so that my JavaScript validation function can throw an alert and return false if no connection.

我已经试过: navigator.onLine - 不能在FF工作(只着眼于是否浏览器离线模式)

I've tried: navigator.onLine - doesn't work in FF (only looks at whether browser in 'offline mode')

AJAX请求到我自己的网站:

AJAX request to my own site:

$.ajax({  
  type: "GET",  
  url: "internet_test.php",  
  async: false, //trying to force a response before continuing
  timeout:8000,
  success: function(ret_text) {
    if(ret_text == 'yes') {
      return true;
    } else {
      alert("No Connection 1");
      return false;
    }
  },
  error: function(x, t, m) {
    if(t==="timeout") {
      alert("No Connection 2");
      return false;
    } else {
      alert("No Connection 3");  //this is the one triggered
      return false;
    }
  }
});

我得到的警报的第三类错误,但随后的形式反正提交。我猜,错误将覆盖我试图指定同步检查的事实,和AJAX之前的JavaScript验证完成后可以返回false。

I get the alert for the third type of error, but then the form submits anyway. I'm guessing that the error overrides the fact that I tried to specify a synchronous check, and the JavaScript validator finishes before the AJAX can return false.

有没有解决这个好办法?更好的办法做到这一点?

Is there a good way around this? Better way to do it?

谢谢!

推荐答案

我会去这样:

  1. 更改提交,按钮(或链接) - 将停止提交表单
  2. 在单击此按钮,从AJAX请求,如果一切正常,则会使form.submit();

这只是一个草案,一切都可以变得更人性化,更强大的无-JS浏览器等。

It's just a draft, everything can be made more user-friendly, more robust for no-js browsers etc.

这篇关于验证表格前,我们提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆