沃梦达 / 编程问答 / php问题 / 正文

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

本文标题为:从 PHP 运行返回错误.阿贾克斯?

基础教程推荐