Jquery/php 输出自定义错误消息

Jquery/php output custom error messagge

本文关键字:错误 消息 自定义 输出 php Jquery      更新时间:2023-09-26

我在表单的输入字段上有一个Ajax自动完成框。在jquery中,我有以下ajax设置

 $.ajax({
    type: "POST",
    url: myUrl,
    data: $("#id__form").serialize(),
    success: function(data){
                  alert("do something");
              },
    error: function (xhr, textStatus, thrownError) { 
                  alert(xhr.status+ " "+ thrownError+ " " + textStatus);
              },
   dataType: "json"
    });

在服务器端,我有这个php代码

  $data = array('type' => 'error', 'message' => 'Error: '.$text);
    header('HTTP/1.1 400 Bad Request');
    header('Content-Type: application/json; charset=UTF-8');
    die(json_encode($data));

无论是成功还是错误,一切正常。但是,我没有弄清楚如何从jquery访问我在php中定义的文本$text

xhr.status 是 400,textStatus 是"error",thrownError 是"错误请求",但没有迹象表明我定义为$text

我错过了什么?

如果你回

显文件中的$text变量,你可以从你的javascript文件访问它。

PHP代码:

     echo $text;

更改为 JavaScript:

    $.ajax({
     type: "POST",
    url: myUrl,
      data: $("#id__form").serialize(),
     success: function(data){
              //do something with the data returned from php file
              alert(data);//<---change to javascript code

          },
         error: function (xhr, textStatus, thrownError) { 
              alert(xhr.status+ " "+ thrownError+ " " + textStatus);
          },
       dataType: "json"
        });

在你的ajax帖子中,你定义了一个json调用。在 php 后端中,您定义了一个数组,因此您可以通过键访问这些参数。您的阵列:

<?php 
    $arr = array();
    $arr['message'] = 'What you like?';
    $arr['errorCode'] = '12345';
    die(json_encode($arr));
?>

在您的情况下,您可以通过添加键来访问数据参数,例如 data.message

成功: function(data){ alert(data.message); }

所以,它必须看起来像这样:

 $.ajax({
     type: "POST",
     url: myUrl,
     data: $("#id__form").serialize(),
     success: function(data){
          alert(data.message+' '+data.errorCode);
          $('#someDivTag').html(data.message);
     },
     dataType: "json"
 });
知道了

,感谢这篇文章 http://wingkaiwan.com/2012/10/21/deserialize-error-in-json-for-jquery-ajax/

问题是成功回调中的变量数据会自动处理 json,但我必须在错误回调中解析它。这有效:

error: function (xhr, ajaxOptions, thrownError) {
        var error = JSON.parse(xhr.responseText);
        alert(error.message);               
}