【问题标题】:Sending array as callbackdata in JS from PHP从 PHP 在 JS 中将数组作为回调数据发送
【发布时间】:2023-03-26 21:08:01
【问题描述】:

我有一个仪表板页面来显示从数据库获取的过去五天的出勤数据。为此,我从脚本调用我在单独的 .js 文件中定义的函数。使用 php 函数,我将数据作为回调数据发送回 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);         
    }

但是这里的控件没有进入 $.each 循环。当我通过以下代码检查拳头是否为数组时,请使用以下代码。 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);
    }
}

【问题讨论】:

  • 新 simRes(simRes::SUCCESS,$dayMap); - 它以 json 响应?你能给出回应的例子吗?
  • 执行此操作: Display.method('getlastPunchSuccessCallBack', function(callBackData) { console.log(callBackData); 打开检查面板并给我们 console.log 的结果
  • 在检查面板中显示为“null”
  • 您可以编辑您的问题并在 simRes 类中提供代码吗?
  • 还有customAction的主体

标签: javascript arrays callback


【解决方案1】:

试试这个:

在您的 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 库,它简化了 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);   
});

【讨论】:

  • 代码可能有问题,因为没测试过,但是逻辑可以理解
  • 我通过更改 PHP 数据库查询尝试了此代码,实际上有错误。现在当我在检查面板中看到时,console.log 以格式打印所有数据:[{"date":"2016-01 -29 08:45:17","total":"09:31:37"},{"date":"2016-01-28 08:58:25","total":"09:49:23 "},{"日期":"2016-01-27 08:55:48","总计":"09:27:35"},{"日期":"2016-01-25 09:07:25 ","total":"08:59:10"},{"date":"2016-01-23 09:14:33","total":"07:11:44"}]
猜你喜欢
  • 1970-01-01
  • 2019-04-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多