更新html表格数据

时间:2019-01-14 11:56:06

标签: javascript php jquery symfony

我的任务是制作一个轮班网络应用程序,该应用程序可以帮助我现有的员工跟踪工人的轮班情况。他们给了我一个网站StaffHub,我应该根据它为我的Web应用程序建模,目前正在日历部分工作。

日历具有三个视图: 1.每月 2.每周一次 3.每天

根据我目前的水平技能,我每周都在工作。 每周完成一次后,我将依次进入“每月”和“每日”

日历的算法:

将年份分为几周,基本上每周从特定日期的星期一开始。今天是1/14/2019,所以直到2019年1月20日为止是有几天的。用户列表组成的这个天数范围是表格,表格的每一行中有7天,其中有一个选择选项,其中包含三个选项“第一班”,“第二班”,“第三班”和“关闭” “ (selectTag仅用于演示目的)。为此,制作了一个html表,该表执行以php和Symfony 2.7编写的POST,将select选项的选择发送到后端并保存在后端。然后GET从后端获取数据。

这是树枝文件的前端:

calendar.html.twig

        <script src="{{ asset('js/jquery.js') }}"></script>
        <script src="{{ asset('js/jquery-ui.min.js') }}"></script>
        <script src="{{ asset('js/moment.min.js') }}"></script>
        <script src="{{ asset('js/moment-range.js') }}"></script>
        <link href="{{ asset('css/jquery-ui.css') }}" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function() {
        //GET funksioni 
        jsonObject = httpGet("http://localhost:8000/users/viewAll").split(',');
        for(i=0;i<jsonObject.length;i++){

        jsonObject[i]=jsonObject[i].replace('"',' ').replace('"',' ').replace('[',' ').replace(']',' ').trim();
        }
        testArray = jsonObject;
        window['moment-range'].extendMoment(moment);
        n = [...Array(7).keys()];
        var curr = new Date; // get current date
        var first = curr.getTime() - 1000*60*60*24*(curr.getDay()-1);
        curr.setTime(first);
        var lastDate = new Date;
        lastDate.setTime(curr.getTime() +  1000*60*60*24*7);
        $('#firstDay').val(moment(curr).format('MMM DD YYYY') + ' ' + moment(lastDate).format('MMM DD YYYY'));
        var a = moment(curr);
        var b = moment(lastDate);
        var range = moment.range(a,b);
        var daysOne = daysFromRange(range);
        var headerData = [""];
        $.each(daysOne,function(index,value){
            daysOne[index] = moment(value).format('ddd DD YYYY');
            headerData.push(daysOne[index]);
        });
        var data  = [headerData]
        for(i=0;i<testArray.length;i++){
            data.push(templateArray(testArray,i));
        }       
            $("#arrow-left").click(function () {
                $(".container").empty();
                $(".container").append("<div></div>");
                curr.setTime(curr.getTime() - 1000*60*60*24*7);
                lastDate.setTime(lastDate.getTime() - 1000*60*60*24*7);
                var p = [];
                $.each(daysFromRange(moment.range(curr,lastDate)),function(index,value){
                            p.push(moment(value).format('ddd DD MM YYYY'));
                });
                data[0] = [""]  
                $.each(p,function(index,value){
                    data[0].push(p[index]);
                });
                $.each($("table th"), function(i,e){
                    $(this).html(data[0][i]);
                });
                $('#firstDay').val(moment(curr).format('MMM DD YYYY') + ' ' + moment(lastDate).format('MMM DD YYYY'));    
            });
            $("#arrow-right").click(function () {
                $(".container").empty();
                $(".container").append("<div></div>");
                curr.setTime(curr.getTime() + 1000*60*60*24*7);
                lastDate.setTime(lastDate.getTime() + 1000*60*60*24*7);
                var p = [];
                $.each(daysFromRange(moment.range(curr,lastDate)),function(index,value){
                            p.push(moment(value).format('ddd DD MM YYYY'));
                });
                data[0] = [""];
                $.each(p,function(index,value){
                    data[0].push(p[index]);
                });
                $.each($("table th"), function(i,e){
                    $(this).html(data[0][i]);
                });
                $('#firstDay').val(moment(curr).format('MMM DD YYYY') + ' ' + moment(lastDate).format('MMM DD YYYY'));
            });
            console.log(data);
            var table = makeTable($('#calendar-container'), data);
            var firstTable = getTableInfoFromArray(getTableData(table));
            var prevTable = firstTable;
             $('select').change(function () {
                currTable = getTableInfoFromArray(getTableData(table));
                $.ajax({
                        type: 'POST',
                        url: '/saveCalendar',
                        //qit sen data duhet me bo 
                        data: JSON.stringify(diffTables(currTable,prevTable)[0]),
                        dataType: 'json',
                        success: function (useremail) {
                            console.log(useremail);
                        },
                        error: function (xhr, status, err) {
                            console.log(xhr);
                         },
                });
                prevTable = currTable;
            });

    });
    function daysFromRange(range){
        var range = range;
        var diff = range.diff('days');
        var array = Array.from(range.by('days'));
        array.splice(-1,1);
        return array;
    };
    function templateArray(array,i){
        var selectTag = "<select id='shift'>" +
        "<option value='volvo' selected='selected'>Volvo</option>" +
        "<option value='saab'>Saab</option>" +
        "<option value='mercedes'>Mercedes</option>" +
        "<option value='audi'>Audi</option>" +
        "</select>";
        return [array[i],selectTag,selectTag,selectTag,selectTag,selectTag,selectTag,selectTag];
    };
    function diffTables(tb,tc){
        c = []; //stack for return values;
        for(i = 0;i < tb.length ; i ++){
            for(j = 0;j < tb[i].length;j++){
                if( !arraysEqual(tb[i][j],tc[i][j])){
                    c.push(tb[i][j]);
                }
            }
        }
        return c;

    }
    function httpGet(theUrl)
    {
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
        xmlHttp.send( null );
        return xmlHttp.responseText;
    }
    function arraysEqual(a1,a2) {
    /* WARNING: arrays must not contain {objects} or behavior may be undefined */
        return JSON.stringify(a1)==JSON.stringify(a2);
    }
    function makeTable(container,data){
            var table = $("<table/>").addClass('CSSTableGenerator');
            table.css("border","1");
            $.each(data,function(rowIndex,r){
                var row = $("<tr/>");
                $.each(r , function(collIndex,c){
                    if(/<\/select>/.test(c)){
                        row.append($("<td/>").html(c));
                    }else{
                    row.append($("<t"+(rowIndex == 0 ?  "h" : "d")+"/>").text(c));
                    };
                });
                table.append(row);
            });
        return container.append(table);
    };
    function appedTableColumn(table,rowData){
        var lastRow = $('<tr/>').appendTo(table.find('tbody:last'));
        $.each(rowData,function(collIndex,c){
            lastRow.append($('<td/>'.text(c)));
        });
    };
    function getTableData(table){
        var data = [];
        table.find('tr').each(function(rowIndex,r){
                var cols = [];
                $(this).find('td,th').each(function(colIndex,c){
                        if($(this).contents().is("select")){
                            cols.push($(this).contents("select").children("option:selected").val());
                        }else{
                            cols.push(c.textContent);
                        }
                });
                data.push(cols);
        });
        return data;  
    };
    function updateTableData(table,data){

    }
    function getTableInfoFromArray(data){
        var p = [];
        for(i = 1;i < data.length;i++){
                var d = [data[0]];
                d.push(data[i]);
                p.push(zip(d));
        };
        for(i=0;i<p.length;i++){
            var user = p[i][0][1];
            p[i].shift();
            p[i].forEach(function(element){
                element.push(user);
            }); 
        };
        return p;
    };
    function zip(arrays) {
    return arrays[0].map(function(_,i){
        return arrays.map(function(array){return array[i]})
    });
}

</script>
<style>
i {
  border: solid black;
  border-width: 0 3px 3px 0;
  display: inline-block;
  padding: 3px;
}
.right:hover { background:green;}
.left:hover { background:green;}
.calendar-selector-buttons{

    width: 50px;
    height: 50px;

}

.right {
    transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);

}

.left {
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
}
select{
  margin: 0px;
  width: 150px;
  font-size: 16px;
  border: 1px solid #ccc;
  height: 34px;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  font-family: "Palatino";

}
textarea{
    background-color: aliceblue;
    margin: 25px;
    margin-bottom: 0px;
    margin-left: 35px;
    border: 1px solid #888; 
    resize: none;
    height: 30px;
    width:  200px;
}
</style>
<div id='calendar-container'>
    <div id='calendar-dates'>
        <div id='calendar-selector-buttons'>
             <div class ='arrow'><i class="arrow left" id="arrow-left"></i><i class="arrow right" id="arrow-right"></i><textarea id='firstDay'></textarea></div>
        </div>
        <div id='calendar-week-selector'>
            <div class="container">
                <div></div>
            </div>
            <div class="users"></div>
        </div>
    </div>
</div>

PHP symfony后端:

 public function getCalendarAction(Request $request,$firstDate,$secondDate){
        /*
            select * from test 
            where date between '03/19/2014' and '03/19/2014 23:59:59'
                    // Qka duna me bo qitu
                   // Kejtsenet n databaze mi marr n baze te dates qi osht ne textarea
                  // P.sh Jun 03 2019 Jun 10 2019
                 // duhet memi kthy kejt schedule per qit date
                // ne URL e shkruj daten, URL date enconding prej textare box e qes nGET request edhe 
               // query stringun e boj n baze dates
            qito sene duna mi bo datetime mu pershtat me databaze
        */
        $sql = "SELECT period,username FROM os_calendarshift where date(period) between date('".DateTime::createFromFormat('Y-m-d', $firstDate)->format('Y-m-d')."')  and date('".DateTime::createFromFormat('Y-m-d', $secondDate)->format('Y-m-d')."');"; 
        //Querying e kryva 
        //tash me kqyr me query databazen
        $em = $this->getDoctrine()->getManager();
        $q = $em->getConnection()->prepare($sql);
        $q->execute();
        $response = new JSONResponse($q->fetchAll());
        $response->setStatusCode(200);
        return $response;
    }

如何更新HTML数据表。 从GET API返回的日期看起来像这样:

[
    {
        "period": "2019-01-07 00:00:00",
        "username": "gbinaku",
        "shift": "audi"
    },
    {
        "period": "2019-01-13 00:00:00",
        "username": "gbinaku",
        "shift": "audi"
    },
    {
        "period": "2019-01-07 00:00:00",
        "username": "abc123",
        "shift": "audi"
    },
    {
        "period": "2019-01-09 00:00:00",
        "username": "ekransiqi",
        "shift": "saab"
    },
    {
        "period": "2019-01-11 00:00:00",
        "username": "gbinaku",
        "shift": "mercedes"
    },
    {
        "period": "2019-01-11 00:00:00",
        "username": "abc123",
        "shift": "mercedes"
    },
    {
        "period": "2019-01-09 00:00:00",
        "username": "burim",
        "shift": "audi"
    },
    {
        "period": "2019-01-07 00:00:00",
        "username": "albertina",
        "shift": "saab"
    },
    {
        "period": "2019-01-08 00:00:00",
        "username": "kini",
        "shift": "audi"
    },
    {
        "period": "2019-01-10 00:00:00",
        "username": "burim",
        "shift": "mercedes"
    },
    {
        "period": "2019-01-08 00:00:00",
        "username": "cvb1",
        "shift": "saab"
    },
    {
        "period": "2019-01-07 00:00:00",
        "username": "ragnar",
        "shift": "mercedes"
    },
    {
        "period": "2019-01-11 00:00:00",
        "username": "cvb1",
        "shift": "saab"
    },
    {
        "period": "2019-01-12 00:00:00",
        "username": "ragnar",
        "shift": "audi"
    },
    {
        "period": "2019-01-13 00:00:00",
        "username": "teab",
        "shift": "mercedes"
    },
    {
        "period": "2019-01-07 00:00:00",
        "username": "cvb1",
        "shift": "audi"
    }
]

但是这里有句号,用户名和Shift,如何从JSON响应信息中相应地更新HTML表。

1 个答案:

答案 0 :(得分:0)

我不太擅长Laravel。我找到了这个。也许它会为您提供一些帮助: https://yajrabox.com/docs/laravel-datatables/master/html-builder