使用jsonencode在AJAX中返回多个数据

时间:2019-11-29 12:52:12

标签: php html ajax

这种情况是我已经传递了值,并且必须获得2个值作为回报。第一个值是一个数组,第二个值是一个简单的字符串。我得到的是字符串的第二个值的结果,但是我不能从返回值中分别从数组中获得第一个值的结果。

我使用的代码为

AJAX代码:

function getprice(dis){
    var roomoccp = $(dis).val();
    $.ajax({
        url: "admin/getroomprice.php",
        type: "POST",
        data: { roomoccp: roomoccp },
        dataType: "json",
        success: function (result) {
            $(dis).parents(".addroom").find(".roomprice").val(result[0].price);
            alert(result[1]);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }
    });
}

现在为getroomprice.php

的查询代码
 <?php
    include "db.php";
    $roomoccp=$_POST['roomoccp'];

    $sql = "SELECT * FROM room where room_id='".$roomoccp."'";
    $result = $conn->query($sql);
    $rows = array();

    while($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }

    $p="Second value is";

    $conn->close();
    print json_encode(array($rows,$p));
?>

如您所见,返回的第一个值是一个数组,我需要该数组中的值

enter image description here

这是从中获取查询值的表。

1 个答案:

答案 0 :(得分:0)

您可以像这样使用第一个数组。

   var data = result[0];
   var count=data.length;
   for(var i=0;i<count;i++)
   {
       var id = data[i].room_id;
       var price = data[i].price;
   }