我有一个PHP脚本设置,根据用户所做的(或未做的,视情况而定)来回显JSON响应:
回复如下:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
每个响应都是这样生成的:
echo $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
这是由pNotify拾取并显示的-可爱。(请参阅下面关于ajax请求的done函数)
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var array = json_to_array(msg);
}
if (array['type'] !== 'none') {
if (array['title'] !== null) {
pushNotification(array['title'], array['response'], array['type'], array['hide']);
} else {
pushNotification(ucfirst(array['type']), array['response'], array['type'], array['hide']);
}
}
ready_status();
});
如果tryParseJSON()
无法验证响应;响应直接写入页面进行调试。
问题是当我echo
多个响应像这样返回时:
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NAct]","title":"Exception","hide":false}
{"type":"error","response":"Script error, please reload the page and try again.
Code: [NDat]","title":"Exception","hide":false}
tryParseJSON()
将其视为一个庞然大物,并将其打印到页面上。
问题
如何将以上两行作为单独的响应,并通过我的函数解析它们,并按子顺序解析到pNotify
,而不将它们组合成一个JSON数组?
解决方案
正如所指出的,这太复杂了。相反,我将每个响应(PHP端)组合成一个数组:
$res['json'][] = $form -> ajax_response('error', 'Script error, please reload the page and try again.<br>Code: [NAct]', 'Exception', false);
然后在脚本的末尾回显:
echo json_encode($res['json');
在客户端,我使用了一个for循环,在每次迭代中将它们发送到pNotify:
request.done(function(msg) {
//validate json response
if (!tryParseJSON(msg)) {
document.write(msg);
} else {
var obj = json_to_array(msg);
}
for (var i=0;i<obj.length;i++) {
if (obj[i]['type'] !== 'none') {
if (obj[i]['title'] !== null) {
pushNotification(obj[i]['title'], obj[i]['response'], obj[i]['type'], obj[i]['hide']);
} else {
pushNotification(ucfirst(obj[i]['type']), obj[i]['response'], obj[i]['type'], obj[i]['hide']);
}
}
}
ready_status();
});
与其创建如此分散的JSON输出,不如将其合并为一个输出字符串。
为此,只需将您当前正在单独输出的两个数组包装在一个数组中,如
$myOutput[0] = responseArray1;
$myOutput[1] = responseArray2;
echo json_encode($myOutput);
通过这种方式,您将获得有效的JSON响应。其他一切都只是一些肮脏的变通方法,会让每个必须审查你工作的人不寒而栗。