【问题标题】:how to return data by ajax in php/mysql/jquery webpage?如何在 php/mysql/jquery 网页中通过 ajax 返回数据?
【发布时间】:2015-02-05 07:53:11
【问题描述】:

内容.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

显示.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? 所以我可以在那里操作数据。

【问题讨论】:

  • 您将在 show.php 中回显的内容将在 ajax 成功回调中可用。 ... dataType: "json", success:function(r){ //+ r 是来自 show.php 的内容回显 }

标签: javascript php html mysql ajax


【解决方案1】:

你必须 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]);
    }

【讨论】:

  • 他们的 json 响应存在一些问题,因为数据是这样来的 {"orderid":["95695","4428516","4428517"]} 但是当我输入 console.log(response.orderid); 时,结果是未定义的
  • 使用 var data=jQuery.parseJSON(response); console.log(data.orderid);
  • {"Order ID":["95695","4428516","4428517"]} 这是我正在尝试的响应 `console.log(data[1].);` 以便打印 95695 但它只是打印未定义
  • 你得到的数据值为 {"Order ID":["95695","4428516","4428517"]}。
  • 很高兴为您提供帮助。如果此答案帮助您接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多