Using ajax to call php and return multiple variables?

后端 未结 5 837
既然无缘
既然无缘 2021-02-04 22:30

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.

This is my JS.



        
相关标签:
5条回答
  • 2021-02-04 22:47

    You can go for Json in PHP and javascript if you want array in response for a ajax request

    PHP Code

    <?php
        $fileId = isset($_GET['id'])?$_GET['id']:0;
        echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
    ?>
    

    Js Code

    jQuery.ajax({
        type: "GET",
        url: 'test.php',
        dataType: "json",
        success: function(response) {
            console.log(response);
            alert(response.num1);
        }
    });
    
    0 讨论(0)
  • 2021-02-04 22:49

    Use a simply string and explode(split) it further in ajax response. Here is PHP code

    <?php
       $fileId = ($_GET['id']);
       echo $num1."|".$num2;
    ?>
    

    Now split(explode) the response with JavaScript

    $.ajax({ 
            url: 'test.php',
            data: { id : lastFileId },
            success: function(output) {
                 var my_arr = output.split("|");
                 console.log(my_arr[0] + "" + my_arr[1]);
            }
    });
    
    0 讨论(0)
  • 2021-02-04 22:50

    You can return as many variables as you want with json_encode().

    Try in your PHP:

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

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

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

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

    var result = $.parseJSON(output);

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

    • result[0] -- $num1 in PHP
    • result[1] -- $num2 in PHP
    0 讨论(0)
  • 2021-02-04 22:58

    convert json to object

    jQuery.ajax({
        type: "GET",
        url: 'test.php',
        dataType: "json",
        success: function(response) {
           item=JSON.parse(response);
            console.log(item);
            alert(item.num1);
        }
    });
    
    0 讨论(0)
  • 2021-02-04 23:08

    you can simply return it like that return ['num1'=>$num1,'num2' => $num2];

    and also, you can access it as followed, respone.num1

    0 讨论(0)
提交回复
热议问题