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 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真
  • ¥15 dpabi预处理报错:Error using y_ExtractROISignal (line 251)
  • ¥15 在虚拟机中配置flume,无法将slave1节点的文件采集到master节点中
  • ¥15 husky+kinova jaco2 仿真
  • ¥15 zigbee终端设备入网失败
  • ¥15 金融监管系统怎么对7+4机构进行监管的