【问题标题】:Sending error message from back to front (php+html)从后到前发送错误消息(php + html)
【发布时间】:2021-05-08 12:06:03
【问题描述】:

我觉得我错过了一些非常简单明了的东西:

我正在使用 GET 从我的 php 文件将响应发送回前面:

添加.php:

foreach ($quote as $key => $value) {
    if (empty($value) or !isset($value)) {
        $error = "$key field is empty";
    }
}

if (!empty($error)) {
    // send error message to front
    $url = "index.php?error=". urlencode($error);
    header("Location:$url");
    exit;
}

我实际上可以在调试器中看到 index.php 获取了这个变量并且它通过了代码,但是我的 div 仍然没有显示在页面上:

索引.php:

<body>
<div class="container">
    <h1>some text here</h1>
    <div class="alert alert-success success my-3" style="display:none">Done!</div>
    <?php

    if(isset($_GET['error'])) {
        echo(<<<EOT
        <div class="alert alert-danger fail my-3">{$_GET['error']}</div>
        EOT);
    }
?>

使用 AJAX 处理成功消息:

<script>
$(document).ready(function() {
    /**
    * Send data after click on submit button
    */
    $(function() {
        $("#add").on('submit', function(e) {

            // stop the following function from happening before click on submit button
            e.preventDefault();

            // send ajax request
            $.ajax({
                url: 'add.php',
                data: $("#add").serialize(),
                type: "post",
                success: function(response) {
                    // check server response
                    if (response == "success") {
                        // show success
                        $('.success').fadeIn(500);
                        setTimeout(function () { location.reload() }, 1000);
                    }
                    //else {
                        // show error message on failure
                    //    $('.fail').fadeIn(1000);
                    //}
                }
            });
        });
    });
})

</script>

任何帮助将不胜感激!

【问题讨论】:

  • 您使用了多少个文件?前后端文件名?
  • index.php 用于前面,add.php 用于后面
  • 显示这些文件的完整代码。如果代码太多,则精确显示。
  • 我已经用更多细节编辑了这个问题,谢谢!

标签: php html error-handling


【解决方案1】:

好吧,问题出在 AJAX 中,我只是用 PHP 添加了错误/成功处理,它就起作用了!

    if (isset($_GET['success']))
{
    echo('<div class="alert alert-success success my-3">Done!</div>');
}

谢谢大家的帮助

【讨论】:

    【解决方案2】:

    您需要在第一次呈现/服务后重置您的网址。 像这样:

    <code>
       if (isset($_GET['error'])) {
            echo(<<<EOT
            <div class="alert alert-danger my-3">{$_GET['error']}</div>
            EOT);
        //need this line
            unset($error);
        }
    </code>
    

    【讨论】:

      【解决方案3】:

      用下面的替换你的 index.php。

      if (isset($_GET['error']))
      {
          echo '<div class="alert alert-danger my-3">'.$_GET['error'].'</div>';
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-12
        • 2014-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-10
        • 2012-02-12
        • 2017-03-03
        相关资源
        最近更新 更多