Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/252.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP json_为JQuery编码错误消息_Php_Json - Fatal编程技术网

PHP json_为JQuery编码错误消息

PHP json_为JQuery编码错误消息,php,json,Php,Json,我的PHP类中有以下方法处理消息并将其发送回JQuery。如果只有一条消息要发回,它就可以正常工作,但如果有多条消息,它会将它们作为单独的json对象发回。消息被发送回ok,但是JQuery给了我一个错误。这些消息如下所示: {"error":true,"msg":"Message 1 here..."}{"error":true,"msg":"Message 2 here"} private function responseMessage($bool, $msg) { $retur

我的PHP类中有以下方法处理消息并将其发送回JQuery。如果只有一条消息要发回,它就可以正常工作,但如果有多条消息,它会将它们作为单独的json对象发回。消息被发送回ok,但是JQuery给了我一个错误。这些消息如下所示:

{"error":true,"msg":"Message 1 here..."}{"error":true,"msg":"Message 2 here"}
private function responseMessage($bool, $msg) {
    $return['error'] = $bool;
    $return['msg'] = $msg;
    if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
        echo json_encode($return);
    }
    ...
}
我的PHP方法如下所示:

{"error":true,"msg":"Message 1 here..."}{"error":true,"msg":"Message 2 here"}
private function responseMessage($bool, $msg) {
    $return['error'] = $bool;
    $return['msg'] = $msg;
    if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
        echo json_encode($return);
    }
    ...
}
我不知道如何改变这一点,以便将多个错误消息放入一个json编码的消息中,但如果它只是一个消息,也可以工作

你能帮忙吗?
谢谢

您可以将错误作为数组发送

$errors = Array();
// some code
$errors[] = ...; // create an error instead of directly outputting it
// more code
echo json_encode($errors);
这将导致如下结果:

[{"error":true,"msg":"Message 1 here..."},{"error":true,"msg":"Message 2 here"}]

看起来您需要附加到数组中,然后在添加所有消息后,输出JSON。当前,函数在任何时候被调用时都会输出JSON:

// Array property to hold all messages
private $messages = array();

// Call $this->addMessage() to add a new messages
private function addMessage($bool, $msg) {
   // Append a new message onto the array
   $this->messages[] = array(
     'error' => $bool,
     'msg' => $msg
   );
}
// Finally, output the responseMessage() to dump out the complete JSON.
private function responseMessage() {
    if (isset($_POST['plAjax']) && $_POST['plAjax'] == true) {
        echo json_encode($this->messages);
    }
    ...
}
输出JSON将是一个对象数组,类似于:

 [{"error":true,"msg":"Message 1 here..."},{"error":true,"msg":"Message 2 here"}]

听起来像是设计问题。您需要构建一个类似$response=array()的对象;然后每次需要添加错误时,只需附加它$响应[]=$errorData;然后,当您完成时,只需json_encode($response)

谢谢大家!!我可以试试看。即使只有一条消息,也总是在json对象周围加上方括号是正常的吗?@user1002039因为你做了一个数组,是的。在接收此JSON的JavaScript代码中,如果只有一个数组元素,则需要访问第一个数组元素。