jQuery ajax 同步失效?

来源:互联网 发布:mac使用u盘拷贝文件 编辑:程序博客网 时间:2024/05/21 21:48

首先感谢本文作者,虽然都是小BUG,但是不注意还是很发现问题。原文地址:http://www.oseye.net/user/kevin/blog/141

今天表单验证时,出现了一个异常现象,耗去了我不少时间呀。

我的验证方法大致如下:

  1. function checkform(){
  2. var mail=$.trim($('#mail').val());
  3. if(mail.length==0){
  4. alert('请填写邮箱');
  5. $('#mail').focus();
  6. return;
  7. }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(mail)){
  8. alert('邮箱格式不正确');
  9. $('#mail').focus();
  10. return;
  11. }else{
  12. $.ajax({
  13. type:"post",
  14. dataType:'json',
  15. async: false,
  16. data:{ mail:mail},
  17. url:"/checkmail",
  18. success: function(res){
  19. if(!res){
  20. alert('该邮箱已经被注册了');
  21. $('#mail').focus();
  22. return;
  23. }
  24. },
  25. error: function(ex){
  26. alert(("操作失败,请联系我们。");
  27. $('#mail').focus();
  28. return;
  29. }
  30. });
  31. }
  32. //其他验证.....
  33. }
但条件不满足时前面两个return都能拦住checkform继续向下执行,而ajax里面的return却阻止不了checkform向下执行!
起初以为设置的同步请求没起作用,查了好多资料,但都是那样设置的。后来使用firefox调试,设置了断点才发现其实已经是同步了,问题就出现在return上,这里的return确实不能阻止程序继续执行。

原因是这里的return只会renturn其自己的域函数,也就是success或error的回调函数。所以可以使用临时变量下即可:

  1. function checkform(){
  2. var mail=$.trim($('#mail').val());
  3. if(mail.length==0){
  4. alert('请填写邮箱');
  5. $('#mail').focus();
  6. return;
  7. }else if(!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(mail)){
  8. alert('邮箱格式不正确');
  9. $('#mail').focus();
  10. return;
  11. }else{
  12. var validate=true;
  13. $.ajax({
  14. type:"post",
  15. dataType:'json',
  16. async: false,
  17. data:{ mail:mail},
  18. url:"/checkmail",
  19. success: function(res){
  20. if(!res){
  21. alert('该邮箱已经被注册了');
  22. validate=false;
  23. }
  24. },
  25. error: function(ex){
  26. alert(("操作失败,请联系我们。");
  27. validate=false;
  28. }
  29. });
  30. if(!validate){
  31. $('#mail').focus();
  32. return;
  33. }
  34. }
  35. //其他验证.....
  36. }
这个问题虽然只是小问题,道理也很容易明白,可我确实耗费了1个多小时,可谓当局者迷呀!!
1 0
原创粉丝点击