PHP如何给一个AJAX的异步请求返回自定义http状态码?

我想要的是返回的xmlhttp.status是自定义的状态码,请问如何实现。
php接受到请求后只能return, 但是return的状态码总是200,http_response_code和header都不能实现,请问有其他办法吗?
下面是代码:

if ($validator->fails()) {        //检查是否出错
    $error = $validator->errors()->all();    //获取错误,后面就是返回错误了,如何实现?
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode(['code'=>418,'msg'=>$error[0]],true));
}

首先是判断表单输入是否合规则,如果不合规则,就返回错误。
用过的方法:

http_response_code(xxx);
return string;
------
http_response_code('xxx');
return string;
------
header('HTTP/1.1 404 Not Found');
return string;

它们,都不行,前台xmlhttp.status检测总是200。
难道说...这个return不行吗?要用echo?

好吧,改为exit()就行了,return不行,谢谢各位了!

http_response_code(418);
exit($error[0]);
阅读 4.8k
3 个回答

是说 http 返回的状态码?还是成功返回的 json 里的某个字段 ?
如果是 http 状态码,如果成功了,就应该是 200 。不建议修改其他的。
而且,你说的 http_response_code header 应该都是可行的。
建议你贴出代码看看

// 使用 header 函数
header("HTTP/1.0 404 Not Found");

HTTP协议里如果没有设置status状态码,那么默认状态码就是200。在HTTP协议中,不同的status code代表服务器端对请求不同的处理结果。例如:200表示服务器已经接受并正确处理客户端请求;201表示新增资源成功;202表示服务器已经接受请求但未处理(排队中);404表示请求的资源不存在;500表示服务器内部异常无法处理客户端请求。
附上部分status code表:

$codes = [

    // Informational 1xx
    100 => 'Continue',
    101 => 'Switching Protocols',

    // Success 2xx
    200 => 'OK',
    201 => 'Created',
    202 => 'Accepted',
    203 => 'Non-Authoritative Information',
    204 => 'No Content',
    205 => 'Reset Content',
    206 => 'Partial Content',

    // Redirection 3xx
    300 => 'Multiple Choices',
    301 => 'Moved Permanently',
    302 => 'Found',  // 1.1
    303 => 'See Other',
    304 => 'Not Modified',
    305 => 'Use Proxy',
    // 306 is deprecated but reserved
    307 => 'Temporary Redirect',

    // Client Error 4xx
    400 => 'Bad Request',
    401 => 'Unauthorized',
    402 => 'Payment Required',
    403 => 'Forbidden',
    404 => 'Not Found',
    405 => 'Method Not Allowed',
    406 => 'Not Acceptable',
    407 => 'Proxy Authentication Required',
    408 => 'Request Timeout',
    409 => 'Conflict',
    410 => 'Gone',
    411 => 'Length Required',
    412 => 'Precondition Failed',
    413 => 'Request Entity Too Large',
    414 => 'Request-URI Too Long',
    415 => 'Unsupported Media Type',
    416 => 'Requested Range Not Satisfiable',
    417 => 'Expectation Failed',

    // Server Error 5xx
    500 => 'Internal Server Error',
    501 => 'Not Implemented',
    502 => 'Bad Gateway',
    503 => 'Service Unavailable',
    504 => 'Gateway Timeout',
    505 => 'HTTP Version Not Supported',
    509 => 'Bandwidth Limit Exceeded'
];

在PHP中使用header设置要返回给客户端的头信息(包括status code),例如:

// 请求的资源已经永久性转移
header("HTTP/1.1 200 OK"); 

// 请求的资源已经永久性转移
header("HTTP/1.1 301 Moved Permanently"); 

// 重定向至指定URL
header ("Location: http://www.example.com/"); 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题