从 PHP 运行返回错误.阿贾克斯?

Return errors from PHP run via. AJAX?(从 PHP 运行返回错误.阿贾克斯?)
本文介绍了从 PHP 运行返回错误.阿贾克斯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果 PHP 脚本在某处失败,有没有办法让 PHP 返回 AJAX 错误代码?我正在学习一个教程并将其输入到我的 PHP 中:

<上一页>$return['error'] = true;$return['msg'] = "无法连接到数据库";

一切都很好,直到我意识到这是 JSON 数据.有没有办法使用标准 $_POST 返回错误并返回 HTML 数据(如触发 jQuery 的 AJAX error: 事件?

解决方案

我不知道 jQuery,但如果它区分成功和不成功(HTTP 200 OK vs. HTTP != 200)Ajax 请求,你可能想要您的 PHP 脚本以不等于 200 的 HTTP 代码响应:

if ($everything_is_ok){header('Content-Type: application/json');打印 json_encode($result);}别的{header('HTTP/1.1 500 内部服务器 Booboo');header('Content-Type: application/json; charset=UTF-8');die(json_encode(array('message' => 'ERROR', 'code' => 1337)));}

Is there a way to get PHP to return an AJAX error code if the PHP script fails somewhere? I was following a tutorial and typed this in to my PHP:

$return['error'] = true;
$return['msg'] = "Could not connect to DB";

And all was well, until I realised it was JSON data. Is there a way to return errors using standard $_POST and returned HTML data (as in, trigger jQuery's AJAX error: event?

解决方案

I don't know about jQuery, but if it distinguishes between successful and unsuccessful (HTTP 200 OK vs. HTTP != 200) Ajax requests, you might want your PHP script respond with an HTTP code not equal to 200:

if ($everything_is_ok)
    {
        header('Content-Type: application/json');
        print json_encode($result);
    }
else
    {
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
    }

这篇关于从 PHP 运行返回错误.阿贾克斯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)