从PHP以JS中的callbackdata形式发送数组

Sending array as callbackdata in JS from PHP

本文关键字:数组 callbackdata PHP JS 中的      更新时间:2023-09-26

我有一个仪表板页面,用于显示从数据库中获取的最近五天的考勤数据。为此,我从脚本中调用了一个我在单独的.js文件中定义的函数。使用php函数,im将数据作为callbackdata发送回Javascript函数。我用的是Javascript,我不知道如何处理这个数组数据。事实上,我是从一个示例应用程序中得到这个想法的,它可以很好地处理字符串,但我不能为数组编码。Index.php页面

       <div class="inner">                              
            <table  class="table table-borderless table-condensed ">
            <thead><tr><th>Date</th><th>Total</th></tr></thead>
            <tbody id ="attendancelist">                    
            </tbody>
            </table>
        </div>
    <script>
    modJs.getlastfiveattendance(); 
   </script>

JS文件:

Display.method('getlastfiveattendance', function() {
    var that = this;
    var object = {"emp_id":empId};  
    var reqJson = JSON.stringify(object);
    var callBackData = [];
    callBackData['callBackData'] = [];
    callBackData['callBackSuccess'] = 'getlastPunchSuccessCallBack';
    callBackData['callBackFail'] = 'getlastPunchFailCallBack';  
    this.customAction('getLastfive','modules=attendance',reqJson,callBackData);
});
Display.method('getlastPunchSuccessCallBack', function(callBackData) {  
    var punches = callBackData; 
    $('#attendancelist').html('');
    var row = '<tr><td>_date_</td><td>_total_</td></tr>';   
    $.each( punches, function(key, value) {  //here i have to process this array to get each data
    var trow = row;     
        trow = trow.replace(/_date_/g,Date.parse(key).toString('MMM d, yyyy (dddd)'));
        trow = trow.replace(/_total_/g,value);
        html += trow;   
    });
    $('#attendancelist').html(html);        
});    
Display.method('getlastPunchFailCallBack', function(callBackData) {     
    this.showMessage("error","Failed to Retrieve data");        
});

在PHP文件中,我获取数据并将其作为数组传递,只需要特定日期的日期和总小时数。

public function getLastfive($req){          
        empid = $req->emp_id;           
        $attendance = new Attendance();
        $attendanceList = $attendance->Find("employee = ? ORDER BY id DESC LIMIT 5",array(empid));          
        $dayMap = array();          
        foreach($attendanceList as $attendance){
            $dayMap[$attendance->in_time] = $attendance->note; //emp in_time as key and the total time as value
        }   
        return new simRes(simRes::SUCCESS,$dayMap);         
    }

但在这里,控制并没有进入$.每个循环。WHen i通过下面的代码来检查冲头是否为数组,通过使用下面的代码。IT显示为非阵列。

if( Object.prototype.toString.call( punches ) === '[object Array]' ) {
    this.showMessage("yes","It's array");
    }
    else
        this.showMessage("No","Its no array");

内部simRes类:

class SimRes{   
    const SUCCESS = "SUCCESS";
    const ERROR = "ERROR";  
    var $status;
    var $data;
    public function __construct($status,$data = null){
        $this->status = $status;    
        $this->data = $data;    
    }   
    public function getStatus(){
        return $this->status;
    }   
    public function getData(){
        return $this->data;
    }   
    public function getJsonArray(){
        return array("status"=>$this->status,"data"=>$this->data);
    }
}

试试这个:

在你的PHP部分:

public function getLastfive($req){          
    $attendance = new Attendance();
    $attendanceList = $attendance->Find("employee = ? ORDERBY id DESC LIMIT 5)",array((int)$req->emp_id));    
    $dayMap = array();   
    // generating array of attendances with key value
    foreach($attendanceList as $attendance){
        $dayMap[] = [
            'date' => $attendance->in_time,
            'total' => $attendance->note
        ];
    }
    return new simRes(simRes::SUCCESS, json_encode($dayMap)); // I don't know if it's already json-ifies result, but if Yes, so remove json_encode
}

在您的HTML(包括lodash-lib,它简化了JS的工作)中:

<script src="https://raw.githubusercontent.com/lodash/lodash/4.6.1/dist/lodash.min.js"></script>

以及在您的JS代码中:

Display.method('getlastPunchSuccessCallBack', function(callBackData) { 
    $('#attendancelist').html(''); // making empty before processing data
    // if response is string, it happens when You don't send application/json content type on response headers
    if(_.isString(callBackData)) {
        callBackData = JSON.parse(callBackData); // parse string make it json
    }
    if(!_.isArray(callBackData)) { // if it's not array of objects, so stop here
        return;
    }
    var punches = callBackData;
    var html = ''; // create empty var to generate html
    _.each(punches, function(punch) { 
        // iterate array of punches and pass punch to iterator function
        // punch is object like {date: "some date", total: "some value"}
        html+='<tr>';
        html+='<td>'+Date.parse(punch.date).toString('MMM d, yyyy (dddd)')+'</td>';
        html+='<td>'+punch.total+'</td>';
        html+='</tr>';
    });
    $('#attendancelist').html(html);   
});