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!');
}
});
});