从PHP分离或拆分Respone到AJAX

时间:2017-08-01 16:28:12

标签: php jquery ajax

  

这是我的PHP代码包含一个令牌数组

$date=$_POST['date'];

$query=mysqli_query($conn,"SELECT tokenno from at_booking where date='$date' and status='Booked'");
while ($row = mysqli_fetch_array($query)) {

    echo json_encode($row);

}
  

这是我的ajax respone代码

date_input.change(function () {
        $("#tokens").show();
        var data=$("#date").val();
        //alert("data"+data);
        $.ajax({
            type : 'POST',
            url : 'tokens.php',
            data : {date: data},

            success:function(response){
                alert("response= "+response);
            }
        });

    });
  

我得到这样的回应

response= {"0":"Token1","tokenno":"Token1"}{"0":"Token2","tokenno":"Token2"}{"0":"Token3","tokenno":"Token3"}{"0":"Token4","tokenno":"Token4"}{"0":"Token5","tokenno":"Token5"}{"0":"Token6","tokenno":"Token6"}{"0":"Token8","tokenno":"Token8"}{"0":"Token7","tokenno":"Token7"}{"0":"Token9","tokenno":"Token9"}{"0":"Token10","tokenno":"Token10"}
  

我有点困惑如何拆分响应,我必须从{“0”:“Token1”,“tokenno”:“Token1”}和“Token2”从{“0”:“Token2”输出“Token1” ”, “tokenno”: “Token2”}

2 个答案:

答案 0 :(得分:0)

我认为你想做更像这样的事情,然后用jquery .each()重温数据

$date=$_POST['date'];

$query=mysqli_query($conn,"SELECT tokenno from at_booking where date='$date' and status='Booked'");
while ($row = mysqli_fetch_array($query)) {

$rows[]=$row;

}
header('Content-Type: application/json');
echo json_encode($rows);

答案 1 :(得分:0)

您可以推入数组,然后将其作为json

返回
$date=$_POST['date'];

$query=mysqli_query($conn,"SELECT tokenno from at_booking where date='$date' and status='Booked'");
while ($row = mysqli_fetch_array($query)) {

    $arr[] = $row;

}

    echo json_encode($arr);
在JS代码中

试试这个

 var values = [];
date_input.change(function () {
        $("#tokens").show();
        var data=$("#date").val();
        //alert("data"+data);
        $.ajax({
            type : 'POST',
            url : 'tokens.php',
            data : {date: data},

            success:function(response){
                $.each(data,function(key,value){
                    values.push(value.tokenno);
                });

                console.log(values);


            }
        });

    });