2014-11-08 140 views
-2

我已经看过很多关于这个问题的答案,但没有一个答案对我来说确实有效。我有一篇文章索引,索引我所有的文章。 如何通过点击删除文件或文章?当点击时,PHP取消链接

代码:

<?php 
$file_name= $file_name.'.php'; 
$file_name_new = uniqid('',true).'.'. $file_name; 
$file_destination ='the_world_news_journal/'.$category.'/' . $file_name_new; 

?> 

    <table> 
     <tr> 
     <td><a onclick='<?php unlink('$file_destination');?>'>delete file</a></td> 
     <td><a onclick='<?php unlink('$file_destination2');?>'>delete file</a></td> 
     </tr> 
    </table> 
+0

您是否收到任何错误? – 2014-11-08 20:26:30

+0

当页面被创建时,PHP在服务器上运行,你不能从HTML调用PHP函数。 – Barmar 2014-11-08 20:26:42

+0

没有错误,它只是在写入并保存取消链接功能后才删除文件。 – Tom 2014-11-08 20:28:15

回答

2

不能调用从HTML onclick属性PHP函数。 PHP在创建页面时运行在服务器上,而不是在客户端上运行。你可以做的是让一个链接,删除文件的脚本:

<td><a href='delete.php?file=<?php echo urlencode($file_destination) ?>'>delete file</a></td> 
<td><a href='delete.php?file=<?php echo urlencode($file_destination2) ?>'>delete file</a></td> 

然后写一个delete.php脚本,删除$_GET['file']命名的文件,并重定向到该页面。

如果您不想重新加载页面,可以使用AJAX调用delete.php脚本。

+0

好吧,我会尝试,而不是谢谢! – Tom 2014-11-08 20:34:19

0

首先,您要创建一个php文件并将其命名为delete.php,并将下面的代码放置在其中。

 <?php 

//The path to your articles folder 
$dirPath = "the_world_news_journal/finance/"; 

    $dir = new DirectoryIterator($dirPath); 

?> 


<table style="width:70%"> 
    <tr> 
    <td><b>Title</b></td> 
    <td><b>Date Posted</b></td> 
    <td><b>Delete Post</b></td> 

    </tr> 
<?php 

foreach ($dir as $fileinfo) {//begin foreach loop 


//if the fileinfo is not equal to . or .. 
if($fileinfo !== "." || $fileinfo !== ".."){//begin if then 

//set the file path retrieving the file name of your articles 
$filePath = "the_world_news_journal/finance/". $fileinfo->getFilename(); 
$filename = $fileinfo->getFilename(); 
$creationdate = date ("F d Y H:i", filectime($filePath)); 
//get the file path, name, creation date, and then and display it in the href inside 
//a td tag 
echo "<tr> 


<td><a href ='$filePath'>$filename</a></td> 
<td>$creationdate</td> 
<td><a class='delete' href='$filePath'>Delete!</a></td> 



</tr> 
"; 


}//end if then 

}//end foreach loop 

?> 
<!--import JQuery to delete a file--> 
<script src="//code.jquery.com/jquery-1.10.2.js"></script> 
<script> 

    //fire event when the .delete class is clicked on 
    $(".delete").on("click",function(event){//begin on click event 

     //stop the link from navigated to another page 
     event.preventDefault(); 

     $.ajax({//begin ajax function 


      url:"delete.php",//the url to your file 
      type:"GET",//type of http request 
      data:"path=" + $(this).attr("href"),//the data to send 
      success:function(data){//begin success 



      }//end success function 


     });//end ajax call 


    });//end on click event 


    </script> 

</table> 
+0

这个作品,谢谢! – Tom 2014-11-09 11:33:32

+0

另一个问题是,当我单击删除时,如何删除该表格行? – Tom 2014-11-09 13:10:19

+0

我为添加了一个id,并插入了以下$('#myTableRow')。remove();到它所说的地方“//如果你想要做成功的事情”问题是当我刷新页面时该行重新出现。 – Tom 2014-11-09 13:26:15