【问题标题】:PHP - End execution of current file from within functionPHP - 从函数内结束当前文件的执行
【发布时间】:2017-08-27 03:51:07
【问题描述】:

我想通过 AJAX 将错误消息作为来自 PHP 的 JSON 数据发送到表单 - 数字,例如数字代码、短信和类别(错误、警告、成功...)

我想知道我是否可以制作函数,它发送 JSON 标头,回显编码数据并最终处理执行它的 CURRENT FILE。 我知道我可以在全局代码中作为返回,但在函数内部?

例如data.php 包含在 ajax.php 中,返回结束 data.php 的处理并继续 ajax.php:

header(json...)
echo json_encode('enter your name', 'warning');
return;

并且在功能中像:

function a($class, $message){
header(json...)
echo json_encode(array($class, $message));
//End processing ONLY file, where it's executed
}

【问题讨论】:

  • 不太清楚你在这里问什么。

标签: php ajax function return


【解决方案1】:

我不完全清楚你在问什么,但我认为这就是你要找的。​​p>

误差函数

function error(array $data, $statusCode = 400) {
    header('Content-Type: application/json');
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

调用函数

error(
    array(
        'message' => 'Name was not filled in',
        'code' => 37
   )
);

输出

Status Code: 400 Bad Data
Content-Type: application/json

{"message": "Name was not filled in", "code": 37}

请注意,您需要确保在将任何输出发送到浏览器之前调用此错误函数,否则它将无法按预期工作

【讨论】:

  • 好的。我现在看到我只需要 json 并退出。谢谢:)
猜你喜欢
  • 1970-01-01
  • 2010-11-18
  • 2017-05-10
  • 2012-07-18
  • 1970-01-01
  • 2021-03-20
  • 2012-05-09
  • 2020-10-19
  • 2017-04-05
相关资源
最近更新 更多