【问题标题】:Use AJAX/JQuery to submit form and show results without reload使用 AJAX/JQuery 提交表单并显示结果而无需重新加载
【发布时间】:2012-01-07 00:01:53
【问题描述】:

我正在尝试使用 jquery 和 ajax 提交表单并在不重新加载的情况下显示结果。就像您典型的 ajax 评论设置一样。

我的 HTML 是这样设置的:

    <form id="create_new_heading" action="/display.php?brand=1" method="post">

          <label for="entry">Heading:</label><br/>
          <input type="text" id="heading" name="heading" maxlength="150"/><br/>

          <input type="submit" value="Add this Heading" />
    </form>
    <div id="result">

   </div>

JS:

    <script>
      /* attach a submit handler to the form */
      $("#create_new_heading").submit(function(event) {

        /* stop form from submitting normally */
        event.preventDefault(); 

        /* get some values from elements on the page: */
        var $form = $( this ),
            term = $form.find( 'input[name="heading"]' ).val(),
            url = $form.attr( 'action' );

        /* Send the data using post and put the results in a div */
        $.post( url, { s: term },
          function( data ) {
              var content = $( data ).find( '#test_me' );
              $( "#result" ).empty().append( content );
          }
        );
      });
    </script>

表单处理器如下所示:

public function write($p) {
    if ( $_POST['type'] )
      $type = mysql_real_escape_string($_POST['type']);
    if ( $_POST['heading'])
      $heading = mysql_real_escape_string($_POST['heading']);
    if ( $type && $heading ) {
      $uniqueid = uniqid();
      $sql = "INSERT INTO headings VALUES('$type','$heading','$uniqueid')";
      return mysql_query($sql);
    } else {
      return false;
    }
  }

我试图按照 jquery 文档来实现这一点,但我似乎无法让它工作。表单提交,条目被放入数据库,但我仍然需要刷新页面才能看到新条目。知道我做错了什么吗?

【问题讨论】:

    标签: php jquery html ajax forms


    【解决方案1】:

    你能检查一下萤火虫,缓存是否会破坏请求。 我遇到了类似的问题,并开始提供 random_id 以及参数和 效果很好。

    正确的方法可以是启用 Cache-Control 标头(或)将过去的时间设置为到期时间。

    【讨论】:

    • 如何在 firebug 中检查这个?
    • 如果你不知道firebug,你可以通过查看服务器日志来检查。如果您正在使用 html、css、jquery,请学习使用 firebug。 1.从addons.mozilla.org/en-US/firefox/addon/firebug安装firebug 2.点击bug图标 3.点击net面板 4.查看你的请求是否灰显
    • 唯一的请求是一个post请求,它没有变灰。
    • 是缓存的问题吗?
    • 酷 :) 当我遇到这个问题时我也很困惑。
    【解决方案2】:

    为什么不拿出.empty()

    $( "#result" ).append( content );
    

    或者试试

    $( "#result" ).html( content );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-29
      • 2012-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多