dongliantong3229 2016-03-25 20:47
浏览 23
已采纳

何时何时不成功:值在jQuery Ajax方法中执行? (标题位置未更改)

I'm submitting a form using jQuery Ajax.

The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).

Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?

Here's my Ajax code:

$(document).ready(function(){
    $("#button").click(function(){
    **//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
    //var **xy**= $("#digits").val();
    //if(xy!=""){
    $.ajax({
        url: "submitform.php",
        type: "POST",
        data: $('#signupform').serialize(),         
        success: function(result){
            $(location).attr('href', 'login2.php');
            },
            error: function(){
            alert(error);
            }
        });
    //  }
    });
});

Here's concerned input tag:

 <form id="signupform" name="form1" method="post" enctype="multipart/form-data">
            <input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......

Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?

  • 写回答

2条回答 默认 最新

  • dsj2222222 2016-03-25 21:01
    关注

    To Question 2:

    If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.

    You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.

    $(document).ready(function() {
      $("#signupform").on('submit', function(e) {
        e.preventDefault();
    
        //FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
        //var **xy**= $("#digits").val();
        //if(xy!=""){
        $.ajax({
          url: "submitform.php",
          type: "POST",
          data: $('#signupform').serialize(),
          success: function(result) {
            $(location).attr('href', 'login2.php');
          },
          error: function() {
            alert(error);
          }
        });
        //  }
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料