使用AJAX调用PHP和返回多个变量? [英] Using ajax to call php and return multiple variables?

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

问题描述

我想用javascript调用PHP脚本,然后将回返回多个变量,以我的javascript这样我就可以对其进行操作。

I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.

这是我的JS。

                $.ajax({ 
                    url: 'test.php',
                    data: { id : lastFileId },
                    success: function(output) {
                        alert(output);
                    }
                });

我的PHP

my PHP

<?php
    $fileId = ($_GET['id']);
    $num1 = 1;
    $num2 = 2;

?>

在这里,我怎么可以返回变量$ NUM1和$ NUM2这样我就可以使用他们在我的JavaScript。这可能吗?

From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?

也这是什么,我有计划做,如果我能做到这一点非常基本的想法。

also this is a very basic idea of what I have planned to do if I can achieve this.

推荐答案

您可以使用 json_en code返回任意多个变量()

尝试在你的PHP:

<?php
echo json_encode(array($num1, $num2));
?>

您可以添加到该数组,$ NUM3,$ num4,... 等等。

You can add to that array , $num3, $num4, ... and so on.

在你的JS,你可以按如下方法访问每一个号码。

In your JS, you can access each number as follows.

第一,您将需要这行code解析EN codeD JSON字符串,在你的成功的功能。

First, you will need this line of code to parse the encoded JSON string, in your success function.

VAR的结果= $ .parseJSON(输出);

这集结果作为一个JSON对象。

That sets result as a JSON object. Now you can access all fields within result:

  • 结果[0] - $ NUM1 在PHP
  • 结果[1] - $ NUM2 在PHP
  • result[0] -- $num1 in PHP
  • result[1] -- $num2 in PHP

这篇关于使用AJAX调用PHP和返回多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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