首页 > 解决方案 > 传递多数据 php 和 javascript

问题描述

我使用此代码进行更改

<script>
$('.BIR').change(function() {
    var id = $(this).val(); //get the current value's option
 $.ajax({
        type:'POST',
        dataType: "json",
        url:'assets.php',
        data:{'id':id,MainM : IR},
        success:function(data){

            $("#IRd").html(data);

        }
    });     
});
   
</script>

我将这个javascript的多变量成功发送到assets.php

<?php 
$id = $_POSt['id'];
$MainM = $_POST['MainM'];

// some php functions here to get the final data 
$Otp  = "xxxxx";
$name = "bbbbb";

?> 

我想将此数据传递回 javascript .. 如果我通过了一个我使用这个

echo $Otp;

这很好用,但我想传递这 2 个或更多变量.. 但我不知道该怎么做.. 所以请帮忙。

标签: javascriptphp

解决方案


我认为使用 json 的理想方式。就像是

echo json_encode(['Otp': $Otp, 'name': $name])

在您的 php 端可以工作,然后您可以在成功函数中使用该数据,如下所示:

success:function(data){

        //you can then use your data like object properties, for an example
        const name = data.name;
        const Otp = data.Otp;

    }

推荐阅读