如何防止AJAX将我发送到页面顶部?

时间:2013-06-07 21:46:38

标签: php ajax jquery

我在新网站底部附近有以下注册表单。加载AJAX响应后,页面会跳到页面顶部。据我所知,我已正确包含“return false”。我错过了什么?谢谢!

## index.php ##

<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
  <form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
    <fieldset>
      <legend><h2 style="align:center;">Enter Your Email Address</h2></legend>               
        <div class="row">
          <div class="offset4 span3">
            <input class="email" type="text" name="email"  id="email" />
          </div>
          <div class="span1">
            <input type="submit" name="submit" value="Join"  class="btn btn-large btn-primary" />
          </div>
        </div>
      <div id="response">
        <? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress();  } ?>
      </div>
    </fieldset>
  </form>
</div>

## and mailing-list.js ##

$(document).ready(function() {
  $('#signup-form').submit(function() {
    // update user interface
    $('#response').html('Adding email address');
    // Prepare query string and send AJAX request
    $.ajax({
      url: 'inc/store-address.php',
      data: 'ajax=true&email=' + escape($('#email').val()),
      success: function(msg) {
        $('#response').html(msg);
      }
    });
    return false;
  });
});

3 个答案:

答案 0 :(得分:3)

$(document).ready(function() {
  $('#signup-form').submit(function(e) {
    e.preventDefault();
    // update user interface
    $('#response').html('Adding email address');
    // Prepare query string and send AJAX request
    $.ajax({
      url: 'inc/store-address.php',
      data: 'ajax=true&email=' + escape($('#email').val()),
      success: function(msg) {
        $('#response').html(msg);
      }
    });
    return false;
  });
});

答案 1 :(得分:1)

我怀疑它是否正在执行默认表单提交行为。使用preventDefault方法防止它。

$(function(){

   $('#signup-form').submit(function(e) {
     e.preventDefault();

     //your existing code goes here

   });

});

答案 2 :(得分:1)

您需要阻止表单提交数据(即使它是同一个文件)。否则页面将在您的ajax调用完成之前重新加载。您可以使用.preventDefault();

执行此操作

尝试

 ...
    $('#signup-form').submit(function(event) {
        event.preventDefault();
        // update user interface
     ...