使用ajax调用删除图像文件

时间:2014-03-20 12:05:02

标签: javascript php jquery ajax

我有一个图像列表,每个图像都有不同的ID。当用户点击特定<img>后跟“删除”按钮时,我想删除该<img>并从服务器中删除该图像文件。我有以下ajax调用,它将实现此目的。

$(document).ready(function () {

    $("img").click(function () {
        var img_id = $(this).attr("id");
        var imagefile = img_id;
        img_id = "#" + img_id;

        $("button").click(function () {          // delete button
            $("#image " + img_id).remove();
            $("button").unbind();

            $.ajax({
                type: "POST",
                url: "deleteimage.php",
                data: imagefile,                        
                success: function(response) {
                // do something
                }
        }); 
    });
});

在删除文件之前,我需要知道图片ID。所以我将它传递给变量然后将其发送到以下php文件。

<?php
    include('config.php');

    if(isset($_POST['imagefile']))
    {
        $imagefile = $_POST['imagefile'];
        $imagepath = "Users/mp4_thumbnails-".$imagefile.".jpg"; 

        unlink($imagepath);
    }
?>

可悲的是,这不起作用。这是我第一次尝试ajax调用。任何意见都将不胜感激。

4 个答案:

答案 0 :(得分:6)

试试这个

$.ajax({
                type: "POST",
                url: "deleteimage.php",
                data: {"imagefile":imagefile},                        
                success: function(response) {
                // do something
                }
        }); 

答案 1 :(得分:0)

        $.ajax({
            type: "POST",
            url: "deleteimage.php",
            data: {imagefile: imagefile}, // here                      
            success: function(response) {
            // do something
            }
        });

答案 2 :(得分:0)

更改

     data: imagefile,

     data: {imagefile, imagefile },

答案 3 :(得分:0)

$.ajax({
    type: "POST",
    url: "deleteimage.php",
    data: "imagefile=" + imagefile,                        
    success: function(response) {
        // do something
    }
});