我有一个在客户端按行显示的文章表。每篇文章都有一个唯一的 ID,并包含一个复选框以指示该文章是否被选中为收藏夹。如果它是最喜欢的,则该复选框已被选中。如果没有,则未选中。现在,如果特定于每一行的复选框条件发生变化,我需要 js 或 jquery 和 ajax 来更新数据库中的表。另一个挑战是我在 cakePHP MVC 环境中工作。
<script type="text/javascript" src="jquery-1.2.1.min.js"></script>
<script type="text/javascript">
function checkbox_click (id, favorite)
{
// see if checkbox is checked
if(favorite==1)
{
$.ajax({
type:'POST',
url:'check_favorite.php', // this external php file isn't connecting to mysql db
data:'id= ' + id + '&favorite=1',
});
}// if
// the checkbox was unchecked
else
{
$.ajax({
type:'POST',
url:'check_favorite.php', // this external php file isn't connecting to mysql db
data:'id= ' + id + '&favorite=0',
});
}//else
}
</script>
--html-- 这是在 foreach 循环内。
echo "<input type='checkbox' id='$rowid;' name='favorite' checked='checked' onclick='checkbox_click('id','favorite',this();' />";
else
echo "<input type='checkbox' id='$rowid;' name='favorite' onclick='checkbox_click('id','favorite',this.checked);' />";
--ajax调用的php文件--
<?php
//Database Variables - with the variables entered it doesn't connect
$dbhost = 'localhost'; // usually localhost
$dbuser = 'username'; // database username
$dbpass = 'password'; // database password
//Establish connection to MySQL database
$con = @mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
die('Unable to connect.' . mysql_error());
mysql_select_db('devcake', $con);
// Get the variables.
$query = "UPDATE mytable SET favorite=".$_POST['favorite'] . "
WHERE id=".$_POST['id'] . ";";
mysql_query($query);
mysql_close($con);
?>