【发布时间】:2018-10-25 16:13:24
【问题描述】:
我需要终止脚本并打印带有一些消息的 JSON。我有以下代码:
header('Content-Type: application/json');
function returnJSON (string $string, bool $success) {
exit(json_encode(['success' => $success, 'message' => $string])); //doesnt print anything
}
if ($someCondition)
returnJSON("This message is not printed...", false);
/*some code...*/
脚本已正确终止,但不会打印输出 JSON。但是,如果我删除该功能并将exit 放入if statement,一切都会很好:
header('Content-Type: application/json');
if ($someCondition)
exit(json_encode(['success' => false, 'message' => "now everything works... but why?"]));
/*some code...*/
谁能给我解释一下?如何终止脚本并在函数内打印 JSON?
编辑:
完整代码:
<?php
require("../tridy/SimpleMailer.php");
header('Content-Type: application/json');
function returnJSON (string $string, bool $success) {
exit(json_encode(['success' => $success, 'message' => $string]));
}
if (isset($_SERVER['HTTP_ORIGIN']))
if (strpos('http://' . $_SERVER['SERVER_NAME'], $_SERVER['HTTP_ORIGIN']) !== 0)
returnJSON("Neplatný HTTP ORIGIN.", false);
else
returnJSON("Chybí hlavička HTTP ORIGIN.", false);
if (empty($_POST["name"]) || empty($_POST["email"]) || empty($_POST["subject"]) || empty($_POST["message"]) ||
empty($_POST["g-recaptcha-response"])) //this condition is true
returnJSON("Nebyly vyplněny všechny pole.", false);
if (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
returnJSON("Email není ve správném formátu.", false);
if (strlen($_POST["name"]) > 20 || strlen($_POST["name"]) < 3 || strlen($_POST["subject"]) > 50 || strlen($_POST["subject"]) < 5)
returnJSON("Pole nesplňují požadavky. Pravděpodobně přesahují maximálaní nebo nesplňují minimální délku.", false);
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcCRVsUAAAAAFMGhWg0Yv9-SMG9OMtFMzKU-ys5&response=".$_POST["g-recaptcha-response"]."&remoteip=".$_SERVER['REMOTE_ADDR']);
if (!json_decode($response)->success)
returnJSON("Google Recaptcha nebyla ověřena", false);
$mailer = new SimpleMailer();
$body = "Zpráva z kolemzeme.tode.cz!<br><b>Od:</b> ".$_POST["name"];
$body .= "<br><b>Zpráva:</b> ";
$mail->from_name = $_POST["name"]." - Kolem Země cestovat denně";
$mail->to = "email@email.cz";
$mail->subject = $_POST["subject"]." - Zpráva z kolemzeme.tode.cz";
$mail->content_type = "text/html";
$mail->body = $body.htmlspecialchars($_POST["message"]);
if ($mail->send() != 1)
returnJSON("Je mi líto, ale vznikla nějaká neznámá chyba při odesílání emailu. Prosím zkuste to znovu později.", false);
else
returnJSON("Email byl úspěšně odeslán. Děkuji za kontaktování, pokusím se ti odpovědět co nejdříve.", true);
编辑 2:
我尝试在 if 语句中调用 exit 并调用 returnJSON 以输出 JSON,但它仍然不起作用:
function returnJSON (string $string, bool $success) {
return(json_encode(['success' => $success, 'message' => $string]));
}
if ($someCondition)
exit(returnJSON("Still doesn't print anything", false));
现在看起来json_encode 没有返回任何东西,但当我测试它时它确实返回了。
【问题讨论】:
-
为我工作。我无法复制。
-
为什么要换成
exit? -
您确定输入
returnJSON? -
@user3783243 我确定我愿意
-
你设置
$someCondition = true了吗?