donglao4370 2013-09-16 04:43
浏览 36
已采纳

使用ajax代码删除上传的图像文件

I want to delete the images that are uploded one by one in php.

I used the following code for displaying the images.On clicking the delete button the image gets deleted from the upload folder.

Code

ImageLap.tpl.php

foreach ( $mainfile as $files ) {
     echo '<img src="'.$files.'" width="100" height="65">';
     echo '<input type="hidden" value="'.$files.'" name="delete_file" />';
     echo '<input type="submit" value="Delete image" />';
 }

ImageLap.php

  if ( array_key_exists ('delete_file', $_POST ) ) {
       $filename = $_POST['delete_file'];
       if ( file_exists ( $filename ) ) {
           unlink( $filename );
           echo 'File '.$filename.' has been deleted';
       }
  }

This code is working well.But the page has to be refreshed on each file deletion. I need a help to delete the files without refreshing the page.I heard that ajax is used for this.But I don't have knowledge in ajax

Please do help me to implement ajax in this code.

  • 写回答

2条回答 默认 最新

  • dsgft1486 2013-09-16 05:08
    关注

    Include jquery in your page header. Then replace

    echo '<input type="hidden" value="'.$files.'" name="delete_file" />';
    echo '<input type="submit" value="Delete image" />';
    

    to

    echo '<input type="hidden" value="'.$files.'" name="delete_file" id="delete_file" />';
    echo '<input type="button" value="Delete image" onclick="delete_image()"/>';
    

    Then write a javascript function to call ajax.

    function delete_image()
    {
      var status = confirm("Are you sure you want to delete ?");  
      if(status==true)
      {
        var file = $("#delete_file").val();
        $.ajax({
          type:"POST",
          url:"ImageLap.php",
          data:{file:file},
          success(html){
           alert('Deleted');
          }
        });
      }
     }
    

    Then in php access file as $_POST['file']

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看