各位大大好,我想要做出一個可以刪除本地端檔案的程式,
但是AJAX卻常常跑到error function顯示錯誤訊息,
懇請各位大大幫忙,以下為程式碼
delete_vedio.js
$('#sure_delete').click(function(){
$.ajax({
type:'POST',
async : true,
url:'ajax_delete_video.php',
dataType:'json',
data:{
fname: ID, //ID 型態為 object
fileDir: i //i 型態為 String
},
success:function(){ //success換成complete才會顯示alert,否則會跳到error
alert('complete');
},
error: function (jqXHR, exception) { //都會執行此,而不是執行success
console.log(jqXHR);
},
});
});
ajax_delete_video.php
<?php
require_once('dbconnect.php');
if(isset($_POST['fname'])) {
$fname = __DIR__."/upload".$_POST['fileDir'].$_POST['fname'];
if (!unlink($fname))
{
echo ("Error deleting $file");
}else{
echo ("Deleted $file");
}
}
?>
jquery ajax 會跳 readyState: 4 錯誤似乎是說你的http請求有成功,但是你POST傳過去的的格式有問題,在這邊提供一個測試的方式給您參考:
Step.1)在"ajax_delete_video.php"同一個資料夾位置新增一個php檔,命名為"testForm.php",然後貼入下列源碼:
<!doctype html>
<html><head><meta charset="utf-8">
<script
src="https://code.jquery.com/jquery-3.4.0.min.js"
integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="
crossorigin="anonymous"></script>
</head>
<body>
<form action="ajax_delete_video.php" method="post">
<label>fileDir: </label><input type="text" name="fileDir" value="001" />
<label>fileName: </label><input type="text" name="fname" value="001.mp3" />
<input type="submit" name="submit" value="傳統表單送出" />
</form>
<hr/>
<button id="sure_delete">AJAX_POST_送出</button>
<script>
$("#sure_delete").click(function(){
ID=$("input[name='fname']").val();
i=$("input[name='fileDir']").val();
$.post("ajax_delete_video.php",{fname:ID,fileDir: i},function(result){
console.log(result);
alert(result);
});
});
</script>
</body>
Step.2) ajax_delete_video.php 作適當修改,範例如下:
<?php
//require_once('dbconnect.php');
if(isset($_POST['fname'])&&isset($_POST['fileDir'])) {
$fname = __DIR__."/upload/".$_POST['fileDir'].'/'.$_POST['fname'];
if (file_exists($fname)) { //先確認檔案存在再執行unlink()
if (!unlink($fname)){
echo ("Error deleting $fname");
}else{
echo ("Deleted $fname");
}
}else{
echo "$fname didn't exist!";
}
}
?>
Step.3)用googleChrome開啟本地端"testForm.php"網址,例如:"http://localhost/oxox/testForm.php"
,然後用裡面的表單送出鈕&AJAX按鈕測試看能不能刪,我測試過是沒問題~