使用ajax删除数据


delete data with ajax

我无法从数据库中删除记录,获取代码正在工作,但删除代码不工作。请帮帮我。。提前感谢

使用ajax获取数据的代码

    $(document).ready(function(){
        done();
    });
    function done(){
        setTimeout(function(){
            updates();
            done();
            }, 200);
    }
    function updates(){
        $.getJSON("fetch.php",function(data){
            $("table").empty();
            $("table").append("<tr><td>Name</td><td>Date</td><td>Delete</td></tr>");
            $.each(data.result, function(){
                $("table").append("<tr><td>"+this['text']+"</td><td>"+this['date']+"</td><td><a id='del' href='"+this['id']+"'>Del</a></td></tr>");
            });
        });
    }

使用ajax删除数据的代码

        $(function() {
    $("#del").click(function(){
    var element = $(this);
    var id = element.attr("id");
    var dataString = 'id=' + id;
    if(confirm("Sure you want to delete this comment?"))
    {
       $.ajax({
       type: "GET",
       url: "del.php",
       data: dataString,
       success: function(){
            }
         });
    }
    return false;
    });
});

php代码del.php

$last_page_id = $_REQUEST['d_i_d'];
$sql = mysql_query("delete from time where id = '{$last_page_id}'");
if(!$sql){
    echo mysql_error();
}else{
    header('location: index.php');
}
Ajax数据:dataString = 'id=' + id;

在php:$last_page_id = $_REQUEST['d_i_d']; 中调用它

您可以使用$_REQUEST['id'] 获取id

请注意,mysql_已被弃用:为什么不应该';我在PHP中使用mysql_*函数吗?

并且您的代码对SQL注入是开放的:http://en.wikipedia.org/wiki/SQL_injection

尝试像这样传递数据:

$.ajax{
    url: 'del.php',
    method: 'GET',
    data: {
        id: // Put your ID value here
    }
    success: function(){
        // Put your success code here
    }
}

看那个片段:

$("#del").click(function(){
var element = $(this);
var id = element.attr("id");
...

id变量将始终保持"del"值,因为您获得的ID属性为$('#del')。