如何通过php / mysql / jquery网页中的ajax返回数据?

时间:2015-02-05 07:53:11

标签: javascript php html mysql ajax

content.php

     $(document).ready(function(){
        var srt=$("#cal1Date1").val();//start date
        var end=$("#cal1Date2").val();//end date

                $.ajax({
            url:"http://localhost/show.php",
            data: {srt:srt,
                end:end
                    },
            type:"POST",
            dataType: "json",
            complete:function(response){

                console.log(response.responseText);
            }}); })}

上面的代码将数据发送到查询日期范围的show.php

show.php     

    include_once "connector.php";
    $sql = "SELECT * FROM `testtable` WHERE  `Request Date` BETWEEN 'start date' AND 'end date' "   ;

            $result = mysqli_query($db,$sql);

            if (mysqli_num_rows($result) > 0) {                         
              while($row = mysqli_fetch_assoc($result)) {
                 echo  $row["Order ID"]; }
                        mysqli_close($db);
                   ?>

以上代码按我们提供的日期范围过滤结果。 它会打印所有已过滤的订单ID'

现在我想知道如何将所有这些订单ID发送回content.php? 所以我可以操纵那里的数据。

1 个答案:

答案 0 :(得分:2)

你必须使用json_encode将响应返回给ajax(content.php)

include_once "connector.php";
$startdate=$_POST['srt'];
$enddate=$_POST['end'];
$sql = "SELECT * FROM `testtable` WHERE  `Request Date` BETWEEN 'start   date'=$startdate AND 'end date'=$enddate "   ;

    $result = mysqli_query($db,$sql);

    if (mysqli_num_rows($result) > 0) {                         
      while($row = mysqli_fetch_assoc($result)) {
         $orderid[]= $row["Order ID"]; }
          mysqli_close($db);
}
     echo json_encode(array('OrderID'=>$orderid));  
           ?>

在ajax Complete函数中获取如下响应,

complete:function(response){

      $rtndata=response.responseText;

          var dat1a=jQuery.parseJSON($rtndata); 

                   var result=dat1a.OrderID;
                   console.log(result[0]);
                   console.log(result[1]);
             console.log(result[2]);
    }