gpt4 book ai didi

jquery - 复选框条件更改时如何使用 ajax 更新 mysql 数据库?

转载 作者:可可西里 更新时间:2023-11-01 07:57:22 25 4
gpt4 key购买 nike

我有一个在客户端按行显示的文章表。每篇文章都有一个唯一的 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 + '&amp;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 + '&amp;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);
?>

最佳答案

这是我使用的代码(感谢 samuel)

 $('input[name=favorite]').live("click",function(){
var id = $(this).attr('id');

if($(this).attr('checked')) {
var favorite = 1;
} else {
var favorite = 0;
}

$.ajax({
type:'GET',
url:'favorites.php',
data:'id= ' + id + '&favorite='+favorite
});
//console.log('id: ' + id + ' Publico: '+publico + 'Value: '+value);

});

关于jquery - 复选框条件更改时如何使用 ajax 更新 mysql 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com