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条)

报告相同问题?