ajax post request

ajax post request met pit
when the button type is submit, ajax post will be submitted twice, the first time a post, the second was get, the feeling is not effective post

 <script>
        function login(e){
             e.preventDefault();//会阻止一次,但是阻止得是post请求,如果不阻止会请求2次
            var formData=$('#login_form').serialize();
            $.ajax({
                type:'POST',
                url:'/user/login',
                data:formData,
                dataType:"json",
                success:function(data){
                    console.log(data);
                   var err_code=data.err_code;
                   alert(data.msg);
                }
            })
        }
      
    </script>
    <input type="submit" class="btn btn-success pull-right" onclick="login(this)" value="登录 "/> 

The most direct solution is to replace the button type button

<script>
        function login(){
            var formData=$('#login_form').serialize();
            $.ajax({
                type:'POST',
                url:'/user/login',
                data:formData,
                dataType:"json",
                success:function(data){
                    console.log(data);
                   var err_code=data.err_code;
                   alert(data.msg);
                }
            })
        }
      
    </script>
<input type="button" class="btn btn-success pull-right" onclick="login()" value="登录 "/>

Guess you like

Origin www.cnblogs.com/zwgblogs/p/11290895.html