Php 发送多个json消息时出错
我对json有一个问题, 我有一个发送json数组的函数Php 发送多个json消息时出错,php,jquery,ajax,json,Php,Jquery,Ajax,Json,我对json有一个问题, 我有一个发送json数组的函数 public function repondMessage($etat=true,$message) { $msg = array($etat,$message); return '{"msg":'.json_encode($msg).'}'; } 当只发送了一个错误时,我就正确地得到了Json数组 像这个: if(a=1) { echo respondeMessage(false,'Error'); } 和jQue
public function repondMessage($etat=true,$message)
{
$msg = array($etat,$message);
return '{"msg":'.json_encode($msg).'}';
}
当只发送了一个错误时,我就正确地得到了Json数组
像这个:
if(a=1)
{
echo respondeMessage(false,'Error');
}
和jQuery:
console.log(data);
var resp = jQuery.parseJSON(data);
console.log(resp);
我得到的结果对我来说很好:
{"msg":[false,"Error"]}
但是当我同时收到两条信息时,当我做这样的测试时
if(a=1)
{
echo respondeMessage(false,'Error');
}
if(b=1)
{
echo respondeMessage(false,'Error2');
}
发生了这样的事情:我不知道如何分离这两个Json
{"msg":[false,"Error"]}{"msg":[false,"Error2"]}
Uncaught SyntaxError: Unexpected token {
通过调用响应函数,您可以多次响应。根据您的代码,我相信其目的是做出如下回应:
{"msg":[false, "Error", "Error2"]}
如果是这种情况,我建议在您的调用上下文中使用以下结构来提供这些结果:
$errors = [];
if($a=1){
$errors[] = 'Error';
}
if($b=1){
$errors[] = 'Error2';
}
if( count( $errors ) ){
respondMessage( true, $errors );
}
根据我的评论,您不能发送多个响应,而是将响应添加到和数组中,然后一次发送所有响应
public function respondMessage($message)
{
$msg = array('msg'=>$message);
//Always send the correct header
header('Content-Type: application/json');
echo json_encode($msg);
//and stop execution after sending the response - any further output is invalid
die();
}
$errors=[];
if($a=1)
{
$errors[]=[false=>'Error'];
}
if($b=1)
{
$errors[]=[false=>'Error2'];
}
if(!empty($errors){
respondMessage($errors);
}
您不能像那样发送多个响应,而是将响应添加到和数组中,然后一次发送所有响应