0

嗨,我为我拥有的评论提要制作了一个赞按钮,但每次我点击它时,它都会重新加载我想做的页面,这样它就不会重新加载页面。我无法在任何地方找到我的问题的答案。我知道我必须使用 javascript 或 AJAX,但因为我不知道如何编码,所以我被卡住了。

这是在我的评论提要所在的页面上。页面名称为 member-index.php

<a href=\"like-exec.php?id=".$rows['ID']."&members_id=".$_SESSION['SESS_MEMBER_ID']."\">like</a>

这是在执行代码的页面上(like-exec.php)

<?php
require('../config/connect.php');
require('../config/config.php');

$sql = "UPDATE comments set `like` = `like`+1 where `ID` = '$_GET[id]'";
$result=mysql_query($sql);


$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("likes", $con);

mysql_query("INSERT INTO likes (members_id, comm_id) VALUES(".$_SESSION['SESS_MEMBER_ID'].", $id)");


mysql_close($con);
header("location: success.php");

?>

在该代码完成后,它被发送到 susses.php,然后将其重定向到 member-index.php。

4

3 回答 3

0
<a class="like" href=\"like-exec.php\" comment-id=".$rows['ID']." members-id=".$_SESSION['SESS_MEMBER_ID']."\">like</a>

尝试使用 JQuery 在 AJAX 中调用 PHP。

$(".like").click(function(){

    $.ajax({
      url: $(this).attr("href"),
      type: "GET",
      data: { comment-id: $(this).attr("comment-id"), members-id: $(this).attr("members-id")},
      success:function(result){

         if(result.success) {
            // Success
         }else{
            // Not success
         }

      },
      error: function(request,status,error){
         // Request error
      }
    });    

});

$_GET["comment-id"]在 PHP 中,您可以使用和获取变量$_GET["members-id"]。当您的脚本成功时,您可以在数组中定义信息,并且可以将其编码为 JSON。之后,您必须使用echo来生成响应:

echo json_encode(array(
   "success" => true
));

如果您的脚本没有成功,您可以这样定义:

echo json_encode(array(
    "success" => false,
    "reason" => "some reason"
));
于 2013-03-05T10:17:13.927 回答
-1

如果您已jquery添加到您的网站,您可以像这样进行 ajax 调用。

首先,我们更新like 链接,使其调用javascript,而不是直接链接到网络服务器。因此,将您的链接更新为:

<a href=\"like-exec.php?id=".$rows['ID']."&members_id=".$_SESSION['SESS_MEMBER_ID']."\" onclick="updateLike($(this));return false;">like</a>

然后我们添加 javascript 来处理 ajax 更新组件。我已将来自服务器的响应作为简单的警报,但您可以尝试直接更新 html 或放置一些内联更新。需要将以下 javascript 添加到页面中:

<script type="text/javascript">
function updateLike(elm)
{
$.ajax({
  type:'GET',
  url: elm.attr('href'),
  error: function(xhr, status, err) {
      // TODO : User friendly error message on ajax fail
      alert("Request Error :" + xhr + status + err);
  }

  success: function(resp) {
      // ajax operation was successful - confirm the like was okay
      if (resp.success) {
         window.location(resp.redirect);
      } else {
         // TODO : User friendly error message on update fail
         alert("Like failed : " + resp.error);
      }
  }
}
</script>

$.ajax()函数执行ajax操作。该error属性处理客户端无法与服务器通信或未获得有效响应的问题。该success属性处理服务器响应的实例。 success将进一步需要检查更新是否成功。

以下是点赞更新的服务器端代码。你已经使用了mysql_*函数,所以我保留了这些函数。但是,请记住,这些函数现在已弃用,取而代之的是MySQLi。您应该考虑更新代码以反映这一点。

<?php
require('../config/connect.php');
require('../config/config.php');

$error = "";

$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
{
   $error = "Unable to connect to database.";
} else {

   // Check the database is available
   $db = mysql_select_db("likes", $con);

   if (!$db)
   {
      $error = "Unable to select like database.";
   } else {
      // Moved update to after connecting with database
      $sql = "UPDATE comments set `like` = `like`+1 where `ID` = '" . $_GET[id] . "'";
      $result = mysql_query($sql);
      if (!$result) { // Check query is successful
         $error .= "Error when updating comment likes.";
      }

      $result = mysql_query("INSERT INTO likes (members_id, comm_id)
      VALUES(".$_SESSION['SESS_MEMBER_ID'].", $id)");
      if (!$result) { // Check insert is successful
         $error .= "Error when inserting member likes.";
      }
   }

   mysql_close($con);
}

// Convert output to a JSON object for jquery to handle
$resp = new Object();
if ($error == "")
{
   $resp->success = true;
   $resp->redirect = "success.php";
} else {
   $resp->error = $error;
   $resp->success = false;
}

echo json_encode($resp);
?>

上面的代码未经测试;所以可能会有错别字/错误/错误,但它应该足以让你开始。

于 2013-03-05T10:20:57.407 回答
-1

PHP/HTML

为您的“喜欢”链接添加一个类,以便我们可以更轻松地在 jQuery 中定位它并将链接的 id 设置为行 id。还值得检查您在页面上的其他地方没有数字 id,因为这些将是简单的 id,很容易在您的标记中的其他地方使用。

<a class="like" id="<?php echo $rows['ID']; ?>" href=\"like-exec.php?id=".$rows['ID']."&members_id=".$_SESSION['SESS_MEMBER_ID']."\">like</a>

jQuery

$('a.like').click(function() {
    // triggered when like link is clicked

    // get the id of this link
    var id = $(this).attr('id');

    // make the AJAX request to the PHP script that updates the database table

    $.ajax({
        type: "GET",
        url: update_likes.php,
        dataType: 'html',
        data: ({ id: id }), // first id is the name, second is the actual id variable we just created
        beforeSend: function(data) {
            // you can do stuff in here before you send the data, display spinner gif etc
            alert('sending!');
        },
        success: function(data) {
            // same here but when the ajax request is successful
            // the data variable is coming from the echo of your PHP script
            alert(data);
        },
        complete: function(data) {
            // yet again but on completion
            alert('complete!');
        }

    });

    // stops the browser following the link (href) in the a tag
    return false;

});

PHP

我们将 ajax 请求发送到的新脚本,但它与您在问题中已有的代码相同。

update_likes.php

<?php
require('../config/connect.php');
require('../config/config.php');

// not sure if session_start(); is in your config but you will need it
// in this script somewhere to do your second query.

// $_GET['id'] is now coming via ajax

$sql = "UPDATE comments set `like` = `like`+1 where `ID` = '$_GET[id]'";
$result=mysql_query($sql);


$con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("likes", $con);

mysql_query("INSERT INTO likes (members_id, comm_id) VALUES(".$_SESSION['SESS_MEMBER_ID'].", $id)");


mysql_close($con);

// header("location: success.php");
// don't need this anymore

// only echo one string from an ajax request so if you need more do some
// concatenation
echo 'successfully updated db!';

?>

最后一点,这些mysql_函数已被弃用,因此请查看 PDO 或 msqli。

PS我还没有测试过代码,但希望它应该可以正常工作。

更新

尝试将点击功能更改为:

$('a.like').click(function(e) {
    // triggered when like link is clicked


    // stops the browser following the link (href) in the a tag
    e.preventDefault();

    // get the id of this link
    var id = $(this).attr('id');

    // make the AJAX request to the PHP script that updates the database table

    $.ajax({
        type: "GET",
        url: update_likes.php,
        dataType: 'html',
        data: ({ id: id }), // first id is the name, second is the actual id variable we just created
        beforeSend: function(data) {
            // you can do stuff in here before you send the data, display spinner gif etc
            alert('sending!');
        },
        success: function(data) {
            // same here but when the ajax request is successful
            // the data variable is coming from the echo of your PHP script
            alert(data);
        },
        complete: function(data) {
            // yet again but on completion
            alert('complete!');
        }

    });
});
于 2013-03-05T10:06:52.773 回答