Ajax请求什么都不返回。为什么?

以下是ajax请求" title="ajax请求">ajax请求。

$.post('delete.php', {'deletearray':deletearray, 'dir':dir}, function(deleted, undeleted){

if(undeleted == 0) {

alert('All ' + deleted + ' files delted from the server');

} else {

alert(deleted + ' files deleted and ' + undeleted + ' files could not be deleted');

}

}, 'json');

这就是delete.php

<?php

if(isset($_POST['deletearray'])) {

$files = $_POST['deletearray'];

$dir = $_POST['dir'];

$deleted = 0;

$undeleted = 0;

foreach($files as $file) {

if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {

$deleted ++;

} else {

$undeleted ++;

}

}

echo json_encode($deleted, $undeleted);

}

return;

?>

运行代码后,它将成功删除文件,但不会显示任何消息。

我也尝试将ajax请求更改为:

 $.post('delete.php', {deletearray:deletearray, dir:dir}, function(deleted, undeleted){

alert("php finished");

}, 'json');

仍然不显示该消息。所以我想在delete.php文件中出了点问题。请帮忙。

回答:

进行jquery + ajax + php的最佳方法如下:

jQuery的:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">

function do_ajax() {

//set data

var myData = new Array();

myData.push({name:'deletearray',value:'deletearray'});

myData.push({name:'dir',value:'dir'});

//ajax post

$.ajax({

dataType: 'json',

url: 'delete.php',

type: 'post',

data: myData,

success: function(returnData) {

if(returnData.undeleted == 0) {

alert('All ' + returnData.deleted + ' files delted from the server');

} else {

alert(returnData.deleted + ' files deleted and ' + returnData.undeleted + ' files could not be deleted');

}

}

});

}

</script>

PHP:

<?php

$myData = $_POST;

if(isset($myData['deletearray']) AND isset($myData['dir'])) {

$files = $myData['deletearray'];

$dir = $myData['dir'];

$deleted = 0;

$undeleted = 0;

foreach($files as $file) {

if(unlink($dir.$file) && unlink($dir.'thumb/'.$file)) {

$deleted ++;

} else {

$undeleted ++;

}

}

print(json_encode(array('deleted' => $deleted, 'undeleted' => $undeleted)));

exit();

}

?>

以上是 Ajax请求什么都不返回。为什么? 的全部内容, 来源链接: utcz.com/qa/404399.html

回到顶部