Ajax-成功返回多个变量 [英] Ajax - success return more than 1 variable

查看:118
本文介绍了Ajax-成功返回多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例:

我对php脚本进行Ajax调用,并得到1个结果. PHP回显如下结果;

I do an Ajax call to a php script and get 1 result. PHP echos out the result like below;

 echo json_encode($result);

然后使用Javascript,以下代码将检索结果.

Then in Javascript, the following code will retrieve the result.

         dataType: "JSON",
         success:function(data){
           var result = data
        }

现在,我正在尝试查看是否可以让PHP脚本回显2个结果,并让Javascript能够通过下面的代码来区分它们;

Now I'm trying to see if I can have PHP script echo out 2 result and have Javascript be able to distinguish them with something like the code below;

echo json_encode($result);
echo json_encode($result2);


dataType: "JSON",
success:function(data1,data2){
    var result1 = data1
    var result2 = data2
}

这可能吗?如果可以,怎么办?

Is this possible? If so, how?

推荐答案

您可以在成功返回AJAX时发送值数组:

You can send an array of values on successful return of AJAX:

echo json_encode(array("data1" => $data1, "data2" => $data2));

并像这样打印:

success: function(data){
    var res1 = data.data1
    var res2 = data.data2
}

这篇关于Ajax-成功返回多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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