【问题标题】:jquery ajax results messagejquery ajax 结果消息
【发布时间】:2011-07-01 19:13:17
【问题描述】:

当用户提交数据字符串作为条目时,我对 php 脚本进行了 ajax 调用,该脚本使用新记录更新我的 MySQL 数据库。 PHP 的一部分是一个 if/else,它将检查条目是否重复。我可以阻止副本更新数据库,但我不知道如何发回一条“错误”消息,上面写着“该记录已存在”......这是我的 jquery: [脚本] $(函数() {

    $(".entry_button").click(function() 
{
    var element = $(this);
    var boxval = $("#entry").val();
    var dataString = 'entry='+ boxval;
        if(boxval=='') {
            alert("Please Enter Some Text");
        } else {

            $("#flash").show();
            $("#flash").fadeIn(400).html('<img src="images/loading.gif" align="absmiddle">&nbsp;<span class="loading">Broifying It...</span>');
            $.ajax({
                    type: "POST",
                    url: "update_data.php",
                    data: dataString,
                    cache: false,
                    success: function(html){
                        $("ol#update").prepend(html);
                        $("ol#update li").slideDown("slow");
                        document.getElementById('entry').value='';
                        $("#flash").hide();
                    }

            });
        }
        return false;
    });
});
[/script]

这是我更新数据库的 php 脚本 (update_data.php):

[php]
include('db.php');
if(isset($_POST['entry']))
{
$date_created = date('Y-m-d H:i:s');
$entry = $_POST['entry'];
$query = "SELECT COUNT(*) AS count FROM table WHERE entry = '$entry'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row['count'] == 0) {
mysql_query("insert into table (entry,date_created) values     ('$entry','$date_created')");
$sql_in= mysql_query("SELECT entry,id FROM table order by id desc");
$r=mysql_fetch_array($sql_in);
$newentry=$r['newentry'];
$id=$r['id'];
?>
<li class="entry bar<?php echo $id; ?>">
<div class="thebro"><span><?php echo $newentry; ?></span></div>
<div class="hr"></div>
<div class="utility-left"><span class="share"><a href="#" title="Share">share</a></span> | <span class="time">days ago</span></div>
<div class="utility-right"><span class="comments">COMMENTS</span> | <span  class="like">LIKE</span></div>
</li>
<?php
} else {
$error = "Sorry, that record already exists";
}   

}
[/php]

我希望能够从 php 脚本中吐出 $error 变量,以便在 ajax 调用中发回并显示在我的 HTML 中的元素中。我已经用谷歌搜索了 ajax 错误消息中的废话,但它们都与标题错误有关,而不是验证错误消息。我也没有使用 json_encode,除非有人想重做上面的那个 jquery 块,以便它作为 json 数据发送。

任何想法都会很棒!

【问题讨论】:

    标签: php jquery mysql ajax custom-errors


    【解决方案1】:

    如果在 PHP 中产生错误,我希望它由 jquery ajax 对象的错误方法处理,而不是通过发送带有一些错误标记 responseText 的正常 HTTP 200 响应来“伪造”它。

    当从 PHP 返回 HTTP 500 时,ajax 错误处理程序不会捕获任何“responseText”。错误处理程序接收 XHR 对象、“错误”状态和“内部服务器错误”错误消息。

    我试图操纵错误信息..

    header( 'HTTP/1.1 500 My Custom Error Message' );
    

    但这没有用。

    起作用的是:

    function errorHandler( $number, $message, $file, $line ) {
        $data = array(
            'message' => $message,
            'line' => $line,
            'file' => $file,
            'trace' => debug_backtrace()
        );
    
        header( 'Debug: ' . json_encode( $data, true ) );
    }
    

    这将使 PHP 返回 HTTP 500,并在额外的标头中包含您的自定义详细信息。

    从 ajax 错误处理程序访问自定义详细信息:

    $.ajax({
        success: function( response ) {
            // ...
        },
        error: function( XHR, status, errorThrown ) {
            $.each( XHR.getAllResponseHeaders().split( '\n' ), function( i, header ) {
                if ( header.substr( 0, 7 ) == 'Debug: ' ) {
                    var error = JSON.parse( header.substr( 7 ) );
                    console.log( error );
                }
            });
        }
    });
    

    【讨论】:

      【解决方案2】:

      只需在你的 phpfile 中回显它并使用:

      document.getElementById('ajaxCatchbox').innerHTML = ajaxRequest.responseText;
      

      来自 ajaxrequest 对象的响应文本会拾取所有回显的内容...不知道 jquery 中的等价物

      【讨论】:

      • $('#ajaxCatchbox').html(ajaxRequest.responseText);
      【解决方案3】:

      在 PHP 中回显错误并退出。然后,在你成功的开始:函数,做这样的事情:

          if(ajaxRequest.responseText.substring(0, 5) === 'Sorry') {
              alert(ajaxRequest.responseText);
              return;
          }
      

      我建议使用子字符串方法,因为它允许您创建各种不同的错误消息,只要它们都以“Sorry”开头。对调试很有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多