PHP Ajax MySQL表行删除

时间:2012-05-24 12:09:04

标签: javascript php mysql ajax sql-delete

我编写了删除MySQL表行的代码。但是当我点击删除图标时,没有任何反应。有人可以告诉我我的代码中还剩下什么吗?

<?php
include_once 'include/DatabaseConnector.php';
$query1="SELECT * FROM MyTable;";
$result1=DatabaseConnector::ExecuteQueryArray($query1);
?>

<script type="text/javascript">
function deleteRow(tableName,colName,id){
    $.ajax({
           type: "POST",
           url: "delete.php",
           data: "tableName=tableName&colName=colName&id=id",
           success: function(msg){
             alert( "Row has been updated: " + msg );
           }
    });
}
</script>

<table id="newspaper-b" border="0" cellspacing="2" cellpadding="2" width = "100%">
<thead>
<tr>
    <th scope="col">Opr</th>
    <th scope="col">Flt Num</th>
    <th scope="col">From</th>
    <th scope="col"></th>
</tr>
</thead>
<tbody>
<?php foreach ($result1 as $row):?>
<tr>
<td><?php echo $row['airlineName'];?></td>
<td><?php echo $row['flightNum'];?></td>                        <td><?php echo $row['from'];?></td>
<td>
  <div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>
<img src='images/delete.png' alt='Delete' />
</div>              
</td>
</tr>
<?php endforeach;?>
</tbody>

delete.php

<?php
    /* Database connection */
    include_once 'include/DatabaseConnector.php';
    if(isset($_POST['tableName']) && isset($_POST['colName']) && isset($_POST['id'])){
        $tableName = $_POST['tableName'];
        $colName = $_POST['colName'];
        $id = $_POST['id'];
        $sql = 'DELETE FROM '.$tableName.' WHERE '.$colName.' ="'.$id.'"';
        mysql_query($sql);
    } else { 
        echo '0'; 
    }
?>

3 个答案:

答案 0 :(得分:1)

  • 您是否检查过您的PHP日志以查看是否有错误?
  • 什么是Ajax.Request?如果您正在使用原型库,那么HTML代码中包含哪些内容?
  • 最后,你确定你的PHP代码被调用了吗? (例如,使用Chrome浏览器中的Web Developper工具,“请求”标签)

答案 1 :(得分:0)

此行有错误

 <div title='Delete' onclick='deleteRow(<?php echo 'flightschedule','flightNum',$row['flightNum']; ?>)'>

这将打印

 <div title='Delete' onclick='deleteRow(flightscheduleflightNumid)'>

您必须将其更改为

  <div title='Delete' onclick='deleteRow("flightschedule","flightNum",<?php $row['flightNum']; ?>)'>

工作。

祝福

更新:要使上述代码也可以添加

<script src="js/jquery.js" type="text/javascript" ></script>

或从互联网上加载

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>  

将Jquery包含在html的标题中。我现在已经测试好了。

答案 2 :(得分:0)

您不会将您的数据发送到delete.php文件,因为在属性日期中,您会严重抓住它们。这是我刚刚测试过的代码(它),这似乎有效。

数据:“tableName =”+ tableName +“&amp; colName =”+ colName +“&amp; id =”+ id +“”,

function deleteRow(tableName,colName,id){
    $.ajax({
           type: "POST",
           url: "delete.php",
           data: "tableName="+tableName+"&colName="+colName+"&id="+id+"",
           success: function(msg){
             alert( "Row has been updated: " + msg );
           }
    });
}