【问题标题】:Send error messages from php to ajax将错误消息从 php 发送到 ajax
【发布时间】:2026-02-15 19:00:01
【问题描述】:

我正在尝试从 php 向 ajax 发送“通知”或错误消息。我正在尝试实现这样的目标:

php:

if (myString == '') {
    // Send "stringIsEmpty" error to ajax
} else if (myString == 'foo') {
    // Send "stringEqualsFoo" error to ajax
}

ajax

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(){
        alert("It works");
    },
    error: function() {
        if(stringIsEmpty) {
            alert("String is empty");
        } else if(stringEqualsFoo) {
            alert("String equals Foo");
        }
    }
});

如何向 ajax 发送错误消息?

更新

这是我拥有的 php 文件。我尝试使用echo 解决方案答案说,但是当我输出data 是什么时(在ajax 中),我得到undefined

<?php
$img=$_FILES['img'];
    if($img['name']==''){
        echo('noImage');
    }else{
        $filename = $img['tmp_name'];
        $client_id="myId";
        $handle = fopen($filename, "r");
        $data = fread($handle, filesize($filename));
        $pvars   = array('image' => base64_encode($data));
        $timeout = 30;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
        $out = curl_exec($curl);
        curl_close ($curl);
        $pms = json_decode($out,true);
        $url=$pms['data']['link'];
        if($url!=""){
            echo "<h2>Uploaded Without Any Problem</h2>";
            echo "<img src='$url'/>";
        }else{
            echo "<h2>There's a Problem</h2>";
            echo $pms['data']['error'];
            header("HTTP/1.1 404 Not Found");
        } 
    }
?>

我在if($img['name']==''){中添加了echo("noImage")

【问题讨论】:

  • 复制并粘贴代码并进行适当的更改。您的问题不清楚。
  • 我终于明白了为什么它会给出奇怪的结果。有没有办法在不向网站输出任何内容的情况下执行您的回答?意思是,没有在实际网站上显示“stringIsEmpty”?

标签: javascript php jquery ajax


【解决方案1】:

只有请求失败才会调用error函数,见http://api.jquery.com/jQuery.ajax/

因此,如果您从 PHP 服务器返回响应,则不会触发错误函数。但是,您可以定义一个函数来根据您从 PHP 发送的响应来处理错误:

success: function(data){
        if (data === "stringIsEmpty") {
           triggerError("stringIsEmpty");
        } else if (data === "stringEqualsFoo") {
           triggerError("stringEqualsFoo");
        }
    },

然后你可以有这样的错误函数:

function triggerError(error) {
    if (error === "stringIsEmpty") {
        alert("Your string is empty!");
    } else if (error === "stringEqualsFoo") {
        alert("Your string is equal to Foo!");
    }
}

如果你发出请求,比如说 post.php,你可以只返回一个字符串:

// Create a function to see if the string is empty
$funcOutput = isStringEmpty();
echo $funcOutput;

或专门用于示例:

echo "stringIsEmpty";

更多信息请见:How to return data from PHP to a jQuery ajax call

【讨论】:

  • 把答案编辑得更清楚一点,如果你从你的 PHP 代码中返回“stringIsEmpty”,你可以像这样在 AJAX 端处理它。
  • 如何从 php 代码中返回“stringIsEmpty”?
  • 用一些例子再次调整。欲了解更多信息,请参阅:*.com/questions/2410773/…
  • 我试过你说的,它显示在网站“foo”上,但它没有调用“alert”。我不希望它显示在网站上,我只想在 ajax 中做一些事情,也就是警报。)
  • 您可以尝试从 $.ajax 调用中删除 processData: false ,这样可以确保返回的数据作为查询字符串返回。否则我也不知道,我不知道你的整个代码结构(也就是你的 php 和 js 文件)
【解决方案2】:

您可以通过更改 php.ini 中的 http 响应代码来触发 jQuery 错误处理程序。任何 4xx 或 5xx 错误都应该有效,但最好留在 rfc 中。

PHP

// no output before the header()-call
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
echo "foo";

jQuery

[...]
error: function(jqxhr) {
    alert(jqxhr.responseText)
}
[...]

【讨论】:

【解决方案3】:

问题是,如果你的 php 响应了,那么从技术上讲它不是错误,必须在成功回调中处理。

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(data){
        alert('The response is: '+data);
        if(data=="empty sting"){
            alert("The string is empty");
        } else if (data == 'foo') {
            alert("The string equals 'foo'");
        } else {
            alert("It works");
        }
    },
});

在你的 PHP 中:

if (myString == '') {
    echo('empty string');
} else if (myString == 'foo') {
    echo('foo');
}

【讨论】:

  • 谢谢!我试过你说的,它显示在网站“foo”上,但它没有调用“警报”。我不希望它显示在网站上,我只想在 ajax 中做一些事情,也就是警报。)
  • @Horay 尝试编辑。如果不起作用,请告诉我第一个警报说什么。
  • 它说:“响应是:未定义”
  • @Horay 哦,我的。再次编辑。
  • 在第一个警报中,变量是响应。你是说数据吗?
【解决方案4】:

发送过程中调用失败时会触发 ajax 方法的“错误”设置。 “超时”、“404”等错误...

如果您想控制服务器的某些响应,您可以在“成功”设置中编写此代码。

$.ajax({
    url: $(this).attr("action"),
    context: document.body,
    data: formData, 
    type: "POST",  
    contentType: false,
    processData: false,
    success: function(response){
          if (response == '') {
               // Send "stringIsEmpty" error to ajax
          } else if (response== 'foo') {
               // Send "stringEqualsFoo" error to ajax
          }
     }
   }

});

PHP 可能是这样的

if (myString == '') {
    echo '';
} else if (myString == 'foo') {
    echo 'foo';
}

【讨论】:

  • 谢谢!我试过你说的,它显示在网站“foo”上,但它没有调用“alert”。我不希望它显示在网站上,我只想在 ajax 中做一些事情,也就是警报。)
【解决方案5】:

我已经尝试了使用带有错误处理的 jQuery AJAX 和 PHP 的引导模型

Javascript 文件:

// add receipt data
        $('#insert_form').on("submit", function(event) {
            event.preventDefault();
            $.ajax({
                url: "includes/user-insert.inc.php",
                method: "POST",
                data: $('#insert_form').serialize(),
                async: true,
                beforeSend: function() {
                    $('#insert').val("Inserting");
                },
                success: function(data) {

                    $('#insert_form')[0].reset();
                    $('#add_reciept').modal('hide');
                    dataTable.ajax.reload(null, false);

                    if (data == "No") {
                        $('#alert-danger').addClass('alert alert-danger');
                        $('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
                        $('#alert-danger').fadeIn().show();
                        setTimeout(function() {
                            $('#alert-danger').fadeOut("slow");
                        }, 8000);
                    } else if (data == "Yes") {
                        $('#alert-success').html('<strong>Well done!</strong> A Record has been Added.');
                        $('#alert-success').addClass('alert alert-info');
                        $('#alert-success').fadeIn().show();
                        setTimeout(function() {
                            $('#alert-success').fadeOut("slow");
                        }, 8000);
                    }


                },
                error: function(err) {
                    $('#alert-danger').addClass('alert alert-danger');
                    $('#alert-danger').html('<strong>Oh snap!</strong> Sorry, that Record wasn\'t Added <b>Try Again</b>');
                    $('#alert-danger').fadeIn().show();
                    setTimeout(function() {
                        $('#alert-danger').fadeOut("slow");
                    }, 8000);
                },
                complete: function(data) {
                    $('#insert').val("Insert");
                }
            });

        });

process.inc.php 文件:

    // check users again or not
  $sql = "SELECT * FROM users_acc WHERE U_Email='$U_Email'";
  $result = mysqli_query($conn, $sql);
  $resultCheck = mysqli_num_rows($result);

  if ($resultCheck > 0) {
    echo 'No';
  } else {

    $query = "
        INSERT INTO users_acc(Firstname, Lastname, U_Email, U_Password, Gender, user_role_id)  
         VALUES('$Firstname', '$Lastname', '$U_Email', '$U_Password', '$Gender' , '$user_role_id')
        ";
    echo 'Yes';
}

【讨论】:

    【解决方案6】:

    所以如果你返回的字符串是空的,或者它等于“foo”,你可能会认为这是一个错误,但是HTTP认为它是成功的,你需要在“success”函数中寻找这些字符串。

    【讨论】:

    • 第一个答案是不完整的,直到我写完我的第二个我才看到。
    • 第一个比你的更完整。