开发者

Disabling scrolling on POST

I have a page that uses a POST to retrieve data from mySQL. However, it's irritating because if I scroll down and click something that does a POST, it kicks the page all the way back up to top. Anyone know of some javascript开发者_StackOverflow社区/jquery plugin that can fix this?


Well, if you do an AJAX POST and replace the page's contents with that which results from the AJAX POST, this scrolling effect will not be a problem.

Keep in mind that this operation might appear seamless for the user (no browser loading).

Let's say you have a form:

<form id="some_form" action="myphp.php">
    <input name="something" value="foo"/>
    <input name="something_else" value="bar" /> 
</form>

and jQuery:

$("#some_form").submit(function() {
   var url = $(this).attr("action");
   var form_data = $(this).serialize();
   // post the same data via an AJAX call
   $.post(url, form_data, function(data) {
      // replace the contents from the received response
      $("html").html(data);
   });
   // disable the default form submit behavior
   return false;
});


did you try Jumping Inside Pages ?

and another example How To Link to a Specific Spot on a Page

<div id="whatever-you-want-to-call-it">
    The content of your div here.
</div>

and the url to get to that point

http://www.pagename.html#whatever-you-want-to-call-it


Try using scrollTop:

$("#some_form").submit(function() {
   var url = $(this).attr("action");
   var form_data = $(this).serialize();
   var currentScrollTop = $('body').scrollTop();

   // post the data via an AJAX call
   $.post(url, form_data, function(data) {
      // replace the contents from the received response
      $(document).html(data);
      $('body').scrollTop(currentScrollTop);
   });

   // disable the default form submit behavior
   return false;
});


It's more clear to use the e.preventDefault(); with jQuery (like Uku Loskit suggested). There is also a mistake in his code (it won't work) so I fixed it.

Here is his code with the change:

<form id="some_form" action="myphp.php"">
    <input name="something" value="foo"/>
    <input name="something_else" value="bar" /> 
</form>

and jQuery:

$("#some_form").submit(function(e) { // e = event object, it has many usefull properties and methods
   e.preventDefault();
   var url = $(this).attr("action");
   var form_data = $(this).serialize();
   // post the same data via an AJAX call
   $.post(url, form_data, function(data) {
      // replace the contents from the received response
      $(document).html(data);
   });
});

By the way, there is no way how to achieve that without javascript if you want to stay at the same page (dont reload, dont change url). If it is used like pagination, then you could add #some-id after the url and then add the id 'some-id' to item which should be at the top when page loads. This will work well - no js needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜