所以我有一个由用户输入动态填充的待办事项列表。每个旁边都有一个复选框,选中后,MySQL 数据库中待办事项的状态应该被修改。
我想这样做:
echo "<input type='checkbox' onclick='changeState($theid);' />";
其中 $theid 是表中的行 ID。
javascript/jquery的changeState()函数是什么样子才能正确更新数据库?
这里的 JavaScript 代码似乎根本不起作用(它被放置在 HTML 文件的 <head>
中:
<script language="javascript">
function changeState()
{
jQuery('body').delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('updatedata.php', {
'rowid': jQuery(this).attr('data-state-id')
//'state': jQuery(this).is(':checked')
});
});
}
</script>
有什么想法吗?
最佳答案
您应该阅读有关 AJAX 调用的更多信息,最好使用 .post()
函数,然后更新服务器端数据库中的数据。
祝你好运。
基于 the documentation of jQuery's .post() 中的示例,你可以实现这样的东西(在带有 jQuery 的 JavaScript 中):
var changeStatus = function(id){
$.post("updateState.php", { 'id': id } );
};
在服务器端(例如在 updateState.php 中):
$id = (int)$_POST['id'];
// here make some query using $id to update the state
// in a manner you prefer
编辑:
但我更喜欢这样的东西:
1) 在服务器端,显示复选框(注意不同的引号和 (int)
转换):
echo '<input type="checkbox" data-state-id="' . (int)$theid . '" />';
2) JavaScript 中的某处(参见 jsfiddle 作为证明):
jQuery(main_container).delegate('input[type="checkbox"][data-state-id]', 'change', function(event){
jQuery.post('update_state.php', {
'id': jQuery(this).attr('data-state-id'),
'state': jQuery(this).is(':checked')
});
});
3) 服务器端的某个位置(在 update_state.php
中):
$id = (int)$_POST['id'];
$state = (bool)$_POST['state'];
$query = 'UPDATE `states` SET `state`="' . $state . '" WHERE `id`="' . $id . '";';
// here execute the query, obviously adjusted to your needs
关于PHP 和 JavaScript 更改 MySQL 中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6286113/