【问题标题】:Submit Form PHP amend to JQuery AJAX提交表单 PHP 修改为 JQuery AJAX
【发布时间】:2019-12-08 20:06:30
【问题描述】:

我希望将以下 php 表单提交转换为 JQuery Ajax 提交。我之前使用过 Ajax 和一些简单的请求,但我不确定如何从 MySQL 提交和返回以下代码的数据。

下面的代码将用户输入条目提交给返回单列行的 MySql 查询。然后一个 While 循环查看这些行并触发另一个 mysql 查询,返回每行的用户喜欢数。

<?php

if(!empty($_POST['Message']))
{
      $userid = session_id();
      $searchStr = get_post($con,'Message');
      $aKeyword = explode(" ", $searchStr);

      $aKeyword = array_filter($aKeyword);

      $stmt = $con->prepare(
          'SELECT m.ID, m.MessageText 
          FROM MessageMain m 
          LEFT OUTER JOIN Likes l on m.ID = l.PostID 
          WHERE MessageText REGEXP ?
          GROUP BY m.ID, m.MessageText ORDER BY count(m.id) desc'
      );

      $regexString = implode('|', $aKeyword);
      $stmt->bind_param('s', $regexString);
      $stmt->execute();
      $result = $stmt->get_result();

       $rowcount=mysqli_num_rows($result);

       echo "<pre> Returned ".  $rowcount . " matches</pre>";

     if(mysqli_num_rows($result) > 0) {
        $row_count=0;
        While($row = $result->fetch_assoc()) {   
            $postid = $row['ID'];
            $row_count++;

                    // Checking user status
                    $status_query = $con->prepare("SELECT COUNT(*) AS type FROM likes WHERE userid = ? AND postid = ?");
                    $status_query->bind_param('ss',$userid,$postid);
                    $status_query->execute();
                    $status_result = $status_query->get_result();
                    $status_row = $status_result->fetch_assoc();
                    $type = $status_row['type'];

                    // Count post total likes
                    $like_query = $con->prepare("SELECT COUNT(*) AS cntLikes FROM likes WHERE postid = ?");
                    $like_query->bind_param('s',$postid);
                    $like_query->execute();
                    $like_result = $like_query->get_result();
                    $like_row = $like_result->fetch_assoc();
                    $total_likes = $like_row['cntLikes'];

?>
                    <div class="post">
                        <div class="post-text">
            <?php

            echo nl2br(htmlentities($row['MessageText'],ENT_COMPAT|ENT_IGNORE, "UTF-8") );

            ?>

             </div>
                        <div class="post-action">

                            <input type="button" value="Like" id="like_<?php echo htmlentities($postid . "_" . $userid); ?>" class="like" style="<?php if($type == 1){ echo "color: #ffa449;"; } ?>" />&nbsp;(<span id="likes_<?php echo $postid . "_" . $userid; ?>"><?php echo htmlentities($total_likes); ?></span>)&nbsp;

                        </div>
                    </div>
        <?php 
                }

    }

}

【问题讨论】:

标签: php jquery mysql ajax


【解决方案1】:

最简单的方法是重写您的 PHP 脚本以仅返回数据,以便您可以在 JS 中使用它来构建 HTML。

我的建议是简单地创建一个数组并将所有数据添加到您的 while 循环中的该数组中,例如:

// Add the array declaration somewhere at the beginning of your script ( outside the while loop )
$likesData = array();

然后在你的while循环中:

$likesData[] = array(
  'ID' => $postid,
  'type' => $type,
  'totallikes' => $total_likes
);

然后在你的while循环之后:

// Return the array as JSON, die script to ensure no other data gets send after the json response
die( json_encode( $likesData ) );

然后在您的 JS ( jQuery ) 中执行以下操作:

// Do the AJAX request
$.post( "yourscript/url/maybephpfile.php", function( jsonResponse ) {
  // Loop over json response
  for( var key of Object.keys( jsonResponse ) ) {
    $( '.your_existing_element' ).append( `<div class="post"><div class="post-text">${jsonResponse[key].totallikes}</div></div>` );
  }
});

希望对您有所帮助,如果您有任何问题,请告诉我。

【讨论】:

  • 谢谢@Lennart。原谅我的无知。 $.post 与 $.ajax({ url:,method:, data: }); 有何不同
  • @CGarden 这只是$.ajax 的简写函数,在大多数情况下您不需要完整的$.ajax 功能,因此他们添加了$.post 和$.get。有关详细信息,请参阅文档:api.jquery.com/jQuery.post
  • 上面的循环似乎在我的屏幕上显示数据一毫秒然后就消失了。不知道为什么这样做....谢谢。新年快乐!
  • @CGarden 抱歉回复晚了,这听起来像是您的 JS 中的一个问题,您是否在现有元素上使用了 append() 方法?如果您改用 html() 功能,则可能会在每个循环上覆盖您的数据。如果您使用 jsfiddle 或类似的工具分享您的 JS,我可以看看并帮助您。
【解决方案2】:

单击按钮时需要从 ajax 表单发送

$.ajax({
  method: "POST",
  url: "some.php",
  data: { message: "message text" }
})
  .done(function( msg ) {
    // process your data back here
    alert( "Data Saved: " + msg );
  });

这里的例子。 https://api.jquery.com/jquery.ajax/ $.post 是 ajax 的快捷方式,post 方法。

我认为最好将文件拆分,而不是把所有的事情都做一个。 form.php -> ajax 请求 -> backend.php -> 使用 ajax 检索到的数据返回到 form.php

【讨论】:

  • 感谢您的回复@Cristo。我理解上面的逻辑,它更复杂的是为每条消息添加喜欢的数量并将其与 HTML 中的点赞按钮等结合起来。
  • 取结果数组。为喜欢的数字添加一列。归还。
  • 不过,我还是会同时执行两个查询。像加入什么的。我认为这会比每行的选择查询更好
猜你喜欢
  • 1970-01-01
  • 2012-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-30
  • 2011-04-23
  • 2012-04-05
相关资源
最近更新 更多