禁用POST上的滚动


Disabling scrolling on POST

我有一个使用POST从mySQL检索数据的页面。然而,这是令人恼火的,因为如果我向下滚动并单击某个执行POST的东西,它会将页面踢回到顶部。有人知道一些javascript/jquery插件,可以解决这个问题吗?

如果您使用AJAX POST并将页面的内容替换为AJAX POST的结果,则此滚动效果将不会成为问题。

请记住,此操作对用户来说可能是无缝的(没有浏览器加载)。

假设你有一个表单:

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

和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;
});

你试过跳转内页吗?

和另一个例子如何链接到页面上的特定位置

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

和到达该点的url

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

尝试使用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;
});

使用e.p preventdefault ();使用jQuery(像Uku Loskit建议的那样)。他的代码中也有一个错误(它不会工作),所以我修复了它。

下面是他修改后的代码:

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

和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);
   });
});

顺便说一下,没有办法如何实现没有javascript,如果你想留在同一个页面(不要重新加载,不要改变url)。如果它像分页一样使用,那么你可以在url后面添加#some-id,然后在页面加载时应该在顶部的item中添加id' some-id'。