Ajax发布成功数据:您可以分开结果吗? [英] Ajax post success data: Can you separate results?

查看:81
本文介绍了Ajax发布成功数据:您可以分开结果吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个简单的ajax发布示例中:

In a simple ajax post example:

$.post('ajax/test.php', function(data) {
$('.result').html(data);
});

是否有任何方法可以将结果数据分开以做两种不同的事情?即:

Is there any way to separate the result data to do two different things? ie:

$.post('ajax/test.php', function(data) {
$('.result').html(data.partone);
$('.other-result').html(data.parttwo);
});

我在页面加载时运行ajax请求,并且试图在一个POST中获取所需的一切.如果可能的话,如何在PHP端定义不同的数据部分? (即:data.partone和data.parttwo)

I run an ajax request when the page is loaded and I'm trying to get everything I need in one POST. If this is possible, how do you define the different data parts on the PHP side? (ie: data.partone and data.parttwo)

推荐答案

您可以将数据作为 JSON 编码的字符串,在关联数组上使用 json_encode(),例如:echo json_encode(array("partone" => "data1", "parttwo" => "data2"));

You can return the data as JSON encoded string, using json_encode() on an associative array, for example: echo json_encode(array("partone" => "data1", "parttwo" => "data2"));

这样,您可以以data.partonedata.parttwo的身份访问它.同样值得一提的是,您应该在$.post()中定义dataType以将其读取为JSON.为此,您需要向其添加另一个参数,以指定要返回的数据类型-JSON.

That way you could access it as data.partone and data.parttwo. Also worth mentioning, you should define the dataType in the $.post() to be read as JSON. For that, you need to add another parameter to it, specifying the type of data you are returning - JSON.

例如:$.post('ajax/test.php', function(data) { ... }, "JSON");

还值得一提的是,您只应从ajax脚本返回此json_encode()输出,否则jQuery将无法正确解析它.

Also worth mentioning, that you should return ONLY this json_encode() output back from the ajax script, else jQuery won't be able to parse it right.

这篇关于Ajax发布成功数据:您可以分开结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆