PHP 使用 header 状态码 return 自定义消息的最佳方式

PHP best way to return custom message with header status code

放置自定义回复消息的最佳位置。我将需要使用 jquery 访问响应消息并将其提醒用户

function return_status($code, $message) {



    //This way
    header("HTTP/1.1 $code $message");
    die();

   //OR This way
   header('Content-Type: application/json');
   header("HTTP/1.1 $code");
   die(json_encode(['code' => $code, 'message' => $message]));
}

虽然 headers 易于访问,但更改与状态代码关联的文本并不是一个好主意。第二种方法最好。

使用你的第二种方法,假设你已经完成了 $.getJSON。

return $.getJSON('my-php-script.php')
    .then(
       function (data) { /* do something with data */},
       function (error) { /* do something with error */}
    )