5

可能重复:
Ajax 内容加载后滚动到顶部

我有一个 ajax 表单,提交时会显示错误或成功消息,理想情况下,我想将浏览器滚动到表单顶部,以便用户可以看到这些消息,但是当我实现它时,它似乎无法正常工作而且我不知道如何修复它:-/它要么滚动不够高,要么刷新?:(我很茫然,如果你能指导我,那就太好了:)

$('#submit').bind('click', function(){
   $('body, html').animate({scrollTop:$('form').offset().top}, 'slow', 'easeInCubic');
   $.ajax({               
      url:$(this).attr('action'),
      type:'POST',              
      data:$('form').serialize(),
      dataType:'json',
      success:function(respond) {
         if(respond.result == 'false') {
            var error_msg = '<h3>Please correct the following errors:</h3><ul>'+respond.errors+'</ul>';
            $('.error_msg').html(error_msg);            
         } else {
            var success_msg = '<h3>Success!</h3>';  
            $('.error_msg').empty();    
            $('.success_msg').html(success_msg);
            $('form').find("input[type=text], textarea").val("");                           
            setTimeout(function() {
               $('.success_msg').slideUp();                             
            }, 5000);
         }      
      }
   });                      
   return false;    
});

HTML:

<form method="post" action="form.php">
   <div class="error_msg"></div>
   <div class="success_msg"></div>
   <label for="name">Name?</label>
   <input type="text" value="" name="name" />
   <label for="email">Email?</label>
   <input type="text" value="" name="email" />
   <input id="submit" type="submit" value="Submit" name="submit" />
</form>
4

1 回答 1

7

Actually i would do it in two ways:

FIRST:

         $(function(){
            function submitForm(){
                $.ajax({
                    url:"a.php",
                    type:"post",
                    success:function(data){
                        alert(data);
                    },
                    complete:function(){
                        $('body, html').animate({scrollTop:$('form').offset().top}, 'slow');
                    }
                });
            }
            $('#submit').click(function(){
                submitForm();
            });
        });

Here i have created a function submitForm() and click of the input type button i am submitting it.

or a better way with a submit button:

SECOND: (I LIKE THIS WAY)

$(function(){
   $('form').submit(function(e){
     e.preventDefault();
       $.ajax({
         url:"a.php",
         type:"post",
         success:function(data){
            alert(data);
         },
         complete:function(){
           $('body, html').animate({scrollTop:$('form').offset().top}, 'slow');
        }
     });
  });
});
于 2012-12-13T17:54:34.950 回答