将错误数据传递给.load()

时间:2013-08-29 00:06:22

标签: jquery

我正在调用PHP函数来删除文件,使用.load:

galleryStatus2$.load('deletePage.php', 
                {pageName : $(e.target).val()},
                function(responseTxt,statusTxt,xhr) {
                if(statusTxt=="success")
                    alert("External content loaded successfully!");
                 if(statusTxt=="error")
                    alert("Error: "+xhr.status+": "+xhr.statusText);
            });

/ * DeletePage.php * /

<?php

$fileName = $_POST['pageName'] . 'xml';  // comes in without a suffix
        $filePath =  $_SERVER['DOCUMENT_ROOT'] . "/users/user_" . $_SESSION['user']['id'] . "/xmls/" . $_POST['fileName'];
        if(!unlink ($filePath)) {
                echo ("<br />delete of $filePath failed");
        }
        else {
            echo ("<br />deletePage.php: delete of $filePath succeeded");
        }

?>

在这种情况下,deletePage.php存在严重错误。它正在寻找的一个POST值未通过,实际的unlink操作失败。但回到客户端,statusTxt报告“成功”和“外部内容已成功加载!”

如何从PHP告诉客户端事情进展不顺利。

由于

1 个答案:

答案 0 :(得分:1)

在您的情况下,您可能需要阅读'responseTxt'而不是'statusTxt'(不更改'deletePage.php':

galleryStatus2$.load('deletePage.php', 
    {pageName : $(e.target).val()},
    function(responseTxt,statusTxt,xhr) {
        if(statusTxt=="success") {
            if(responseTxt.indexOf('succeeded') >= 0) {
                alert("External content loaded successfully!");
            } else {
                alert("Error: "+xhr.status+": "+xhr.statusText);
            }
        } else if(statusTxt=="error")
            alert("Error: "+xhr.status+": "+xhr.statusText);
    }
);

第二个选项: 的.js

galleryStatus2$.load('deletePage.php', 
    {pageName : $(e.target).val()},
    function(responseTxt,statusTxt,xhr) {
        if(statusTxt=="success") {
            if(responseTxt) {
                var obj = jQuery.parseJSON(responseTxt);
                if(obj && obj.status == 'success') {
                    //success do whatever you need to do
                    alert(obj.msg);
                } else {
                    //fail do whatever you need to do
                    alert(obj.msg);
                }
            }
        } else if(statusTxt=="error")
            alert("Error: "+xhr.status+": "+xhr.statusText);
    }
);

.PHP

<?php
$fileName = $_POST['pageName'] . 'xml';  // comes in without a suffix
$filePath =  $_SERVER['DOCUMENT_ROOT'] . "/users/user_" . $_SESSION['user']['id'] . "/xmls/" . $_POST['fileName'];
$response = array('status' => '', 'msg' => '');
if(!unlink ($filePath)) {
    $response['status'] = 'success';
    $response['msg'] = '<br />delete of $filePath failed';
} else {
    $response['status'] = 'error';
    $response['msg'] = '<br />deletePage.php: delete of $filePath succeeded';
}
json_encode($response);
?>