有人能请建议我可能会在下面的代码中出错吗?我正在尝试使用Ajax和JQuery来编辑html表中的某些字段。编辑工作在前端,但当我刷新页面时,编辑会消失,因为它们没有写入数据库。到目前为止我的代码有云:在Jquery中使用Ajax进行内联编辑
的index.php - 我试图使name字段编辑
echo "<table cellpadding='0' cellspacing='0' border='0' class='table table-striped' id='datatable'>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>City</th>
<th>County</th>
<th>Phone</th>
<th>Mobile</th>
<th>Admin</th>
</tr>
</thead><tbody>";
while($row = $sth->fetchObject()){
echo '<tr>
<td class="edit name '.$row->customer_id.'">'.$row->name.'</td>
<td>'.$row->address_line_1.',<br />'.$row->address_line_2.',<br />'.$row->address_line_3.'</td>
<td>'.$row->city.'</td>
<td>'.$row->county.'</td>
<td>'.$row->phone.'</td>
<td>'.$row->mobile.'</td>
<td><div class="btn-group">
<a class="btn btn-primary" href="#">Admin</a>
<a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#"><span class="caret"></span>
</a><ul class="dropdown-menu">
<li><a href="mailto:'.$row->email.'"><i class="icon-envelope"></i>Email</a></li><li><a href="#"><i class="icon-pencil"></i>Edit</a></li><li><a id="'.$row->customer_id.'" class="delete"/><i class="icon-trash"></i>Delete</a></li>
</td></tr>';
}
echo "</tbody></table>";
jQuery的
<script>
$(document).ready(function(){
$('td.edit').click(function(){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
$(this).addClass('ajax');
$(this).html('<input id="editbox" size="'+$(this).text().length+'" type="text" value="' + $(this).text() + '">');
$('#editbox').focus();
}
);
$('td.edit').keydown(function(event){
arr = $(this).attr('class').split(" ");
if(event.which == 13)
{
$.ajax({ type: "POST",
url:"includes/edit-customer.php",
data: "value="+$('.ajax input').val()+"&rownum="+arr[2]+"&field="+arr[1],
success: function(data){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}});
}
}
);
$('#editbox').live('blur',function(){
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
});
});
</script>
编辑customer.php
<?php
//MySQL Database Connect
require 'config.php';
if(isset($_POST['rownum']))
{
update_data($_POST['field'],$_POST['value'],$_POST['rownum']);
}
print_r($_POST);
function get_data()
{
$query = $dbh->prepare("SELECT * FROM customer");
$query->execute();
return $query;
}
function update_data($field, $data, $rownum)
{
$query = $dbh->prepare("UPDATE customer SET ".$field." = '".$data."' WHERE customer_id = ".$rownum;);
$query->execute();
}
?>
分
我的数据库中的客户表中的列CUSTOMER_ID,名称,地址行,address_line_2,address_line_3,市,县,电话,手机,电子邮件
嗨@Tim Withers谢谢你,我已经修复了这个声明,但我似乎遇到了致命错误:调用该行的成员函数prepare() – 2012-03-13 22:55:22
你需要声明数据库处理程序('$ dbh ')作为全局或将其传递给函数本身。 '$ dbh'未初始化,否则不是PDO对象。 – 2012-03-13 22:58:30
非常好,修复了错误,我在这个过程中学到了新东西,非常感谢! – 2012-03-13 23:08:18