我第一次使用数据表,但遇到了一个小问题。我的第一次尝试是这样编写PHP代码的:
<?php
$city = ($_GET['city']);
$sort = ($_GET['sort']);
$sortorder = ($_GET['sortorder']);
if ($city == "la"){
$citylong = "Los Angeles";
}
if ($city == "oc"){
$citylong = "Orange County";
}
if ($city == "sf"){
$citylong = "San Francisco";
}
?>
<h5>Reservations for <?php echo $citylong; ?></h5>
<table id="datatable1" class="table table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Booking Date</th>
<th>Name</th>
<th>Class</th>
<th>Pick Up</th>
<th>Duration</th>
<th>Drop Off</th>
<th>Age</th>
<th>Coverage</th>
<th>Quote</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
include 'dbconfig.php';
$sql="SELECT bookingid, bookingdatetime, firstname, lastname, address, city, state, country, post, dlnum, dlexp, dlcountry, phone, email, addcomments, pickuploc, droploc, pickupdatetime, dropdatetime, class, numofdrivers, coverage, driversage, roadsideass, afterhoursdrop, promo, quotedprice, status, remoteip FROM reservations WHERE pickuploc='" . $city . "' ORDER BY " . $sort . " " . $sortorder;
$result = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($result)) {
$bookingdate = new DateTime($row['bookingdatetime']);
$bookingdatetimefancy = $bookingdate->format('m/d/y \@\ h:i a');
$pickupdatetime = new DateTime($row['pickupdatetime']);
$pickupdatetimefancy = $pickupdatetime->format('m/d/y \@\ h:i a');
$dropdatetime = new DateTime($row['dropdatetime']);
$dropdatetimefancy = $dropdatetime->format('m/d/y \@\ h:i a');
$pickupdate = new DateTime($pickupdatetime->format('Y-m-d'));
$dropdate = new DateTime($dropdatetime->format('Y-m-d'));
$inbetween = $pickupdate->diff($dropdate)->days;
$duration = str_pad($inbetween, 3, "0", STR_PAD_LEFT);
$statusConfirmed = "";
$statusUnconfirmed = "";
$statusOpen = "";
$statusClosed = "";
$statusCanceled = "";
if($row['status']=="Confirmed"){
$statusConfirmed = 'selected';
}
if($row['status']=="Unconfirmed"){
$statusUnconfirmed = 'selected';
}
if($row['status']=="Open"){
$statusOpen = 'selected';
}
if($row['status']=="Closed"){
$statusClosed = 'selected';
}
if($row['status']=="Canceled"){
$statusCanceled = 'selected';
}
if ($row['pickuploc'] == $row['droploc']) {
$otherdropoff = "";
}else{
$otherdropoff = " (" . $row['droploc'] . ") ";
}
echo '<tr>
<td>' . $row['bookingid'] .'</td>
<td>' . $bookingdatetimefancy .'</td>
<td>' . $row['firstname'] . " " . $row['lastname'] .'</td>
<td>' . $row['class'] .'</td>
<td>' . $pickupdatetimefancy .'</td>
<td>' . $duration . " days" .'</td>
<td>' . $dropdatetimefancy . $otherdropoff .'</td>
<td>' . $row['driversage'] .'</td>
<td>' . $row['coverage'] .'</td>
<td>$' . $row['quotedprice'] .'</td>
<td><select name="resstatus" id="resstatus' . $row['bookingid'] .'" onchange="changeresstatus(' . $row['bookingid'] . ');">
<option ' . $statusConfirmed. ' value="Confirmed">Confirmed</option>
<option ' . $statusUnconfirmed . ' value="Unconfirmed">Unconfirmed</option>
<option ' . $statusOpen . ' value="Open">Open</option>
<option ' . $statusClosed . ' value="Closed">Closed</option>
<option ' . $statusCanceled . ' value="Canceled">Canceled</option>
</select></td>
</tr>';
}
?>
</tbody>
</table>
这是很草率的,并且由于我以后希望添加自动更新功能,所以我认为最好使用JSON数组传输所有内容,因此现在可以这样进行:
<?php
$city = ($_GET['city']);
include 'dbconfig.php';
$sql="SELECT bookingid, bookingdatetime, firstname, lastname, address, city, state, country, post, dlnum, dlexp, dlcountry, phone, email, addcomments, pickuploc, droploc, pickupdatetime, dropdatetime, class, numofdrivers, coverage, driversage, roadsideass, afterhoursdrop, promo, quotedprice, status, remoteip FROM reservations WHERE pickuploc='" . $city . "'";
$result = mysqli_query($conn,$sql);
$arr = array();
while($row = mysqli_fetch_array($result)) {
$bookingdate = new DateTime($row['bookingdatetime']);
$bookingdatetimefancy = $bookingdate->format('m/d/y \@\ h:i a');
$pickupdatetime = new DateTime($row['pickupdatetime']);
$pickupdatetimefancy = $pickupdatetime->format('m/d/y \@\ h:i a');
$dropdatetime = new DateTime($row['dropdatetime']);
$dropdatetimefancy = $dropdatetime->format('m/d/y \@\ h:i a');
$pickupdate = new DateTime($pickupdatetime->format('Y-m-d'));
$dropdate = new DateTime($dropdatetime->format('Y-m-d'));
$inbetween = $pickupdate->diff($dropdate)->days;
$duration = str_pad($inbetween, 3, "0", STR_PAD_LEFT);
$statusConfirmed = "";
$statusUnconfirmed = "";
$statusOpen = "";
$statusClosed = "";
$statusCanceled = "";
if($row['status']=="Confirmed"){
$statusConfirmed = 'selected';
}
if($row['status']=="Unconfirmed"){
$statusUnconfirmed = 'selected';
}
if($row['status']=="Open"){
$statusOpen = 'selected';
}
if($row['status']=="Closed"){
$statusClosed = 'selected';
}
if($row['status']=="Canceled"){
$statusCanceled = 'selected';
}
if ($row['pickuploc'] == $row['droploc']) {
$otherdropoff = "";
}else{
$otherdropoff = " (" . $row['droploc'] . ") ";
}
array_push($arr, array(
'id' => $row['bookingid'],
'bookingdatetime' => $bookingdatetimefancy,
'name' => $row['firstname'] . " " . $row['lastname'],
'class' => $row['class'],
'pickupdatetime' => $pickupdatetimefancy,
'duration' => $duration . " days",
'dropdatetime' => $dropdatetimefancy . " " . $otherdropoff,
'age' => $row['driversage'],
'coverage' => $row['coverage'],
'quote' => "$" . $row['quotedprice'],
'status' => $row['status']
));
}
// Send the $date_ranges as JSON.
$json = json_encode($arr); // '[{"start": "2019-08-18", "end": "2019-08-19"}]'
echo $json;
这是我的Java脚本:
function getres() {
$.ajax({
type : 'get',
url : 'reservations2.php?city='+document.getElementById("cityselect").value,
dataType: 'json',
cache: false,
success : function(result)
{
if (document.getElementById("cityselect").value == "la"){
city = "Los Angeles";
}
if (document.getElementById("cityselect").value == "oc"){
city = "Orange County";
}
if (document.getElementById("cityselect").value == "sf"){
city = "San Francisco";
}
restitle.innerText = "Reservations for "+city;
$('#resdatatable').dataTable({
data: result,
destroy: true,
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
{ data: 'class', title: 'Class' },
{ data: 'pickupdatetime', title: 'Pick up' },
{ data: 'duration', title: 'Duration' },
{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
{ data: 'coverage', title: 'Coverage' },
{ data: 'quote', title: 'Quote' },
{ data: 'status', title: 'Status' },
]
});
}
});
}
如您所见,当更改为通过数组传递数据时,我失去了选择下拉菜单的功能。如何添加下拉菜单回去?
我需要放回选择,我需要它们具有与行ID匹配的唯一ID,并且我需要它们具有onchange函数。
答案 0 :(得分:0)
您可以为“状态”列定义renderer
。
我还创建了一个jQuery插件,以替代性地扫描表并将每行的最后一个调用更改为下拉列表。
我还注释掉了标题和字段以减少列数。
let statusList = [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}];
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) {
return k.id === data;
}).length > 0;
if (isKnown) {
return $('<select>', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected')
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
let result = getResult();
let statusList = getStatusList();
$('#resdatatable').dataTable({
data: result,
destroy: true,
columns: [
{ data: 'id', title: 'ID' },
{ data: 'bookingdatetime', title: 'Booking Date' },
{ data: 'name', title: 'Name' },
//{ data: 'class', title: 'Class' },
//{ data: 'pickupdatetime', title: 'Pick up' },
//{ data: 'duration', title: 'Duration' },
//{ data: 'dropdatetime', title: 'Drop off' },
{ data: 'age', title: 'Age' },
//{ data: 'coverage', title: 'Coverage' },
//{ data: 'quote', title: 'Quote' },
{
data: 'status',
title: 'Status',
render: function(data, type, row) {
let isKnown = statusList.filter(function(k) { return k.id === data; }).length > 0;
if (isKnown) {
return $('<select>', {
id: 'resstatus-' + row.id, // custom id
value: data
}).append(statusList.map(function(knownStatus) {
let $option = $('<option>', {
text: knownStatus.text,
value: knownStatus.id
});
if (row.status === knownStatus.id) {
$option.attr('selected', 'selected')
}
return $option;
})).on('change', function() {
changeresstatus(row.id); // Call change with row ID
}).prop('outerHTML');
} else {
return data;
}
}
}
]
});
/**
* jQuery plugin to convert text in a cell to a dropdown
*/
(function($) {
$.fn.createDropDown = function(items) {
let oldTxt = this.text();
let isKnown = items.filter(function(k) { return k.id === oldTxt; }).length > 0;
if (isKnown) {
this.empty().append($('<select>').append(items.map(function(item) {
let $option = $('<option>', {
text: item.text,
value: item.id
});
if (item.id === oldTxt) {
$option.attr('selected', 'selected')
}
return $option;
})));
}
return this;
};
})(jQuery);
// If you remove the renderer above and change this to true,
// you can call this, but it will run once...
if (false) {
$('#resdatatable > tbody tr').each(function(i, tr) {
$(tr).find('td').last().createDropDown(statusList);
});
}
function getResult() {
return [{
'id': 1,
'bookingdatetime': '2019-11-01',
'name': 'John Doe',
//'class': '',
//'pickupdatetime': '',
//'duration': '',
//'dropdatetime': '',
'age': 18,
//'coverage': '',
//'quote': '',
'status': 'Confirmed'
}, {
'id': 2,
'bookingdatetime': '2019-11-01',
'name': 'Jane Doe',
//'class': '',
//'pickupdatetime': '',
//'duration': '',
//'dropdatetime': '',
'age': 21,
//'coverage': '',
//'quote': '',
'status': 'Open'
}, {
'id': 3,
'bookingdatetime': '2019-11-08',
'name': 'Mary Sue',
//'class': '',
//'pickupdatetime': '',
//'duration': '',
//'dropdatetime': '',
'age': 16,
//'coverage': '',
//'quote': '',
'status': 'Closed'
}, {
'id': 4,
'bookingdatetime': '2019-12-15',
'name': 'Charlie Brown',
//'class': '',
//'pickupdatetime': '',
//'duration': '',
//'dropdatetime': '',
'age': 25,
//'coverage': '',
//'quote': '',
'status': 'Unknown'
}];
}
function getStatusList() {
return [{
id: 'Confirmed',
text: 'Confirmed'
}, {
id: 'Unconfirmed',
text: 'Unconfirmed'
}, {
id: 'Open',
text: 'Open'
}, {
id: 'Closed',
text: 'Closed'
}, {
id: 'Canceled',
text: 'Canceled'
}];
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/css/dataTables.material.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="resdatatable" class="table table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Booking Date</th>
<th>Name</th>
<!-- <th>Class</th> -->
<!-- <th>Pick Up</th> -->
<!-- <th>Duration</th> -->
<!-- <th>Drop Off</th> -->
<th>Age</th>
<!-- <th>Coverage</th> -->
<!-- <th>Quote</th> -->
<th>Status</th>
</tr>
</thead>
<tbody></tbody>
</table>