简体   繁体   English

通过Jquery post()返回多个值

[英]Return multiple values through Jquery post()

I've returned 2 dates from a PHP script through $.post() . 我已经通过$.post()从PHP脚本返回了2个日期。 Then I'm trying to break up the results into two variables (the commented out portion under the console.log) , instead of appearing in one variable. 然后,我尝试将结果分成两个变量(console.log下的注释部分),而不是出现在一个变量中。

Below is the jquery code: 下面是jquery代码:

   $.post('api/displayDBSetTimes.php', function(data) {
    var obj = JSON.parse(data);
    var htmlToInsert = obj.map(function (item) {
     console.log(item.DB_ST);

     /* var db_st = item.DB_ST;
      var db_et = item.DB_ET;
      return db_st + " " + db_et;*/
      return item;

    });
    $('#oecd').html(htmlToInsert);
  });

The PHP is below. PHP在下面。 I formatted the dates in the PHP script before sending out in JSON. 在以JSON发送之前,我先用PHP脚本格式化了日期。 The commented out jquery code above worked before I formatted the dates in PHP: 在用PHP格式化日期之前,上面注释掉的jquery代码起作用了:

 <?php 
 include_once("../include/sessions.php");
 $select = "SELECT start_time AS DB_ST, end_time AS DB_ET FROM countdown WHERE tid = 1;";
     $query = mysqli_query($dbc, $select);

if($query){
    $out = array();
    while ($row = $query->fetch_assoc()) 
    {
        $out[] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ST']));
        $out[] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ET']));
    }

    // encode array as json and output it for the ajax script
    echo json_encode($out);
    }
   ?>

Every time I try to refer to the PHP variable in the jQuery $post() function (ie. item.DB_ST in the console.log) it returns as undefined , but if I remove the PHP variable reference, the 2 dates come back as one big string. 每次我尝试在jQuery $post()函数中引用PHP变量(即console.log中的item.DB_ST )时,它都返回undefined ,但是如果我删除了PHP变量引用,则2个日期将返回为一大串。 I don't want that. 我不要 I don't know why it's coming back undefined if I reference one part of the array. 我不知道为什么引用数组的一部分会返回未定义状态。

Could someone help me? 有人可以帮我吗? Would ajax() be better for something like this? ajax()对于这样的东西会更好吗? The help would be much appreciated. 帮助将不胜感激。

You need to use associative array in PHP, in order to achieve key-value pairs. 您需要在PHP中使用关联数组,以实现键值对。

$out['DB_ST'] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ST']));
$out['DB_ET'] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ET']));

Set associative arrays in your PHP file... 在您的PHP文件中设置关联数组...

$out['DB_ST'] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ST']));
$out['DB_ET'] = date('D, m-d-Y H:i:s A', strtotime($row['DB_ET']));

And in your $.post you have to indicate the response is going to be in JSON format... 在$ .post中,您必须指示响应将采用JSON格式...

$.post('api/displayDBSetTimes.php', function(data) {

    /* Here you can access directly to data.DB_ST and data.DB_ET */

},'json');

I hope it helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM