php 如何对ajax返回的数据进行告警?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5272225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:49:44  来源:igfitidea点击:

How to Alert the returned data of ajax?

phpjquery

提问by user628961

I have a jQuery page with AJAX, and is submitted in a separate PHP file that has no UI. so what i want is if say for example an insert query in my PHP file will fail, an echo(your insert failed)in my PHP will be alerted in my jQuery page. how to do that?

我有一个带有 AJAX 的 jQuery 页面,并在一个没有 UI 的单独 PHP 文件中提交。所以我想要的是,如果说例如我的 PHP 文件中的插入查询将失败,echo(your insert failed)我的 PHP 中的一个将在我的 jQuery 页面中发出警报。怎么做?

something like this alert(data);

像这样的东西 alert(data);

回答by oshirowanen

EDIT 2:

编辑2:

Alerting anything that PHP echos:

警告 PHP 回显的任何内容:

function get_data() {
    $.ajax({
        url: 'get_data.php?rand=' + Math.random(),
        type: 'GET'
        success: function(results) { 
            alert(results);
        }
    });
}

EDIT 1:

编辑 1:

If you want the errors to appear in an alert, do this:

如果您希望错误出现在警报中,请执行以下操作:

for debugging ajax, you can check the xhr, status, and error like so:

为了调试ajax,你可以像这样检查xhr、状态和错误:

function get_data() {
    $.ajax({
        url: 'get_data.php?rand=' + Math.random(),
        type: 'GET',
        error: function(xhr, status, error) {
            alert(status);
            alert(xhr.responseText);
        },
        success: function(results) { 
            /* clear old results, then display the new results */
            $("#divResults").empty().append(results);
        }
    });
}

But this might not always display the full message, especially if the error message contains lots of data. it might end up going off the screen.

但这可能并不总是显示完整的消息,尤其是在错误消息包含大量数据的情况下。它可能最终会离开屏幕。

ORIGINAL ANSWER:

原始答案:

for debugging ajax, you can check the xhr, status, and error like so:

为了调试ajax,你可以像这样检查xhr、状态和错误:

function get_data() {
    $.ajax({
        url: 'get_data.php?rand=' + Math.random(),
        type: 'GET',
        error: function(xhr, status, error) {
            /* clear old error message, then display the new php error message */
            $("#divErrorMessages").empty().append(status);
            $("#divErrorMessages").append(xhr.responseText);
        },
        success: function(results) { 
            /* clear the error message first */
            $("#divErrorMessages").empty();

            /* clear old results, then display the new results */
            $("#divResults").empty().append(results);
        }
    });
}

In your HTML you should have the 2 divs

在您的 HTML 中,您应该有 2 个 div

<div id="divResults"></div>
<div id="divErrorMessages"></div>

回答by rdamborsky

You can use successhandler in $.ajaxcall as diEcho wrote. Inside of this handler, you can decide by some flag whether your PHP operation succeeded or failed.

您可以success$.ajax调用中使用处理程序,如 diEcho 所写。在这个处理程序中,您可以通过一些标志来决定您的 PHP 操作是成功还是失败。

errorhandler of $.ajaxis more likely for ajax call fail, than for status of requested operation.

error处理程序$.ajax更可能导致 ajax 调用失败,而不是请求操作的状态。

Edit:

编辑:

applying to example by diEcho:

diEcho 适用于示例:

$.ajax({
  url: "/post/post_url.php",
  type: "POST",
  data: parameters,
  success: function(data){
    alert('ajax call finished successfully');
    if (!data.insertedOk) {
      alert(data.message);
    } else {
      // insert succeeded
    }
  },
  error: function(){
    alert('ajax call failure');
    // this mean, /post/post_url.php calling failed (file not found etc...)
  }
});

EDIT2:

编辑2:

in PHP you could use following

在 PHP 中,您可以使用以下内容

if ($queryExecutedSuccessfully) {
    $return['insertedOk'] = true;
    $return['message'] = 'Your success message';
} else {
    $return['insertedOk'] = false;
    $return['message'] = 'Error message when insert fails.';
}
echo json_encode($return);

回答by Akarun

Regarding the code of @diEcho, You also need to test in success: function()your returned answer with a status code (wrote by PHP).

关于@diEcho 的代码,您还需要success: function()使用状态代码(由 PHP 编写)在返回的答案中进行测试。

In other hand, you can force the error in your PHP script by sending an "Error 500" header, that generate the "Fail" callback. But it's not a good way !

另一方面,您可以通过发送“错误 500”标头来强制 PHP 脚本中的错误,从而生成“失败”回调。但这不是一个好方法!

In your PHP:

在您的 PHP 中:

if (true === $QueryHasFail) {
    header('HTTP/1.1 500 Internal Server Error'); // <--- Ajax Callback error: function() 
    echo "Oupss, somethink wrong!";
} else {
    echo "Yeah, great"; // <--- Ajax Callback success: function()
}
exit(0);

More information here: http://www.rachaelarnold.com/dev/archive/trigger-ajax-error-event

更多信息在这里:http: //www.rachaelarnold.com/dev/archive/trigger-ajax-error-event

回答by diEcho

try like this

像这样尝试

$.ajax({
  url: "/post/post_url.php",
  type: "POST",
  data: parameters,
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

Reference

参考

回答by Greg

To alert what is echoed in your PHP, "data" is passed into the success function as the first parameter, which is then output in an alert in this example:

为了提醒您的 PHP 中回显的内容,“数据”作为第一个参数传递到成功函数中,然后在此示例中输出到警报中:

$.ajax({
  url: "/post/post_url.php",
  type: "POST",
  data: parameters,
  success: function(data){
    alert(data);
  },
  error: function(jqXHR, textStatus, errorThrown){
    alert('Failure: ' + textStatus + ". Error thrown: " + errorThrown);
  }
});

回答by thosleaf

I know this is an old topic, but as i found it searching for something similar, i decided to add some information that could be useful for later searches.

我知道这是一个古老的话题,但当我发现它在搜索类似的东西时,我决定添加一些对以后搜索有用的信息。

I think a solutionto this could be aproached by sendingthe appropriate header() or http_response_code($HTTP_ERROR_CODE); in your PHP Script, depending on the answers of your PHP Script. You can find related info in this posts:

我认为可以通过发送适当的header() 或 http_response_code($HTTP_ERROR_CODE)解决这个问题;在您的PHP Script 中,取决于您的PHP Script的答案。您可以在此帖子中找到相关信息:

How to make a ajax call to a php page a success or error?

如何使对 php 页面的 ajax 调用成功或错误?

How to send a server error response using php?

如何使用php发送服务器错误响应?

The function you select(header or http_response_code) it depends on the version of PHP you are using, it seems that http_response_code is available from PHP 5.4.

您选择的函数(header 或 http_response_code)取决于您使用的 PHP 版本,似乎 http_response_code 从 PHP 5.4 开始可用。

A workaround to avoid "PHP version crosscompiling" might be achieved by coding your own http_response_code in the case that testing for it existance results in failure, as is suggested in this other post of php.net:

避免“PHP 版本交叉编译”的解决方法可以通过编码您自己的 http_response_code 来实现,以防测试它的存在性导致失败,正如 php.net 的另一篇文章中所建议的那样:

http://php.net/manual/en/function.http-response-code.php

http://php.net/manual/en/function.http-response-code.php

Latter, on your HTML/jQuery document, you can check your request.fail, request.done and request.always to retrieve the information provided by your PHP Script to use it at your convenience.

稍后,在您的 HTML/jQuery 文档中,您可以检查 request.fail、request.done 和 request.always 以检索您的 PHP 脚本提供的信息,以便在您方便的时候使用它。

Hope this helps.

希望这可以帮助。