2017-09-20 59 views
0

我已经从PHP脚本通过$.post()返回了2个日期。然后我试图将结果分解为两个变量(console.log下的注释部分),而不是显示在一个变量中。通过jquery post()返回多个值

下面是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); 
    }); 

的PHP如下。我在用JSON发送消息之前在PHP脚本中格式化日期。上述注释掉jQuery代码的工作之前,我格式化PHP日期:

<?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); 
    } 
    ?> 

每次我试着参考PHP变量jQuery的$post()功能(即item.DB_ST中的console.log)它返回undefined,但如果我删除PHP变量引用,则2个日期将作为一个大字符串返回。我不想那样。如果我引用数组的一部分,我不知道它为什么会返回undefined。

有人可以帮助我吗? ajax()会比这更好吗?非常感谢帮助。

回答

0

在你的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'])); 

而在你的$。员额,你必须表明响应将是JSON格式...

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

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

},'json'); 

我希望它有帮助。

+0

是的!谢谢! – hnewbie

+0

好听到!祝你有美好的一天,快乐的编码! –

0

您需要在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'])); 
+0

hnewbie,你能否接受我的答案,因为它实际上早些发布? :) 谢谢! – cassini

+0

看起来我只能接受一个答案。 :(自从A.Iglesias帮我解决了两端问题(PHP&Jquery),我觉得他的回答比较完整。 – hnewbie

+0

没问题啦!干杯 – cassini