多个JSON数组作为响应-AJAX&PHP
Multiple JSON arrays as reponses - AJAX & PHP
我有一个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响应。其他一切都只是一些肮脏的变通方法,会让每个必须审查你工作的人不寒而栗。
相关文章:
- php&js-将电子邮件添加到输入文本中
- PHP&CSS:如何获得表中每一行的悬停效果
- 无法使用AJAX&PHP
- 如何安全地获取&使用Facebook应用程序访问令牌发送通知使用PHP&Javascript
- 如何将Angular 2用于各种网站&使用PHP作为后端的模块
- 如果没有添加PHP&Javascript
- 将本地MySQL数据库与PHP&谷歌地图上的JavaScript
- IE不发送发布数据PHP&jQuery
- css&js文件在php中不起作用
- PHP&jQuery联系人表单错误
- 如何不允许在使用PHP的自动完成表单中不在数据库中的值&JS
- Jquery、AJAX&PHP,表单提交不起作用
- 启动&使用php停止iframe
- (PHP&JavaScript)a href添加按钮赢得'我不适用于Mozilla,但适用于IE和谷歌
- 动态路由PHP&AngularJS
- 是php json_encode&AJAX破坏了我的数组
- php&ajax检索post数据失败
- 无限滚动(mysql,php&js)循环问题
- 如何将DIV ID的值保存到数据库PHP&MySQL
- & php post receive problem