我有一张文章表格,客户端以行显示。每篇文章都有一个唯一的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);
?>