我在视图中将数据附加在表中,但是我想显示部分数据自定义,而不是仅仅返回数据库数据。
我目前从我的数据库id, title & price
返回了3个数据:
id's
表演checkbox
0
表演input field
我实际上只需要返回所有标题。
HTML
<div class="mt-20 options"></div>
AJAX
<script>
$(function(){
$('select[name="options"]').on('change', function() {
var addressID = $(this).val();
if(addressID) {
$.ajax({
url: '{{ url('admin/getoptions') }}/'+encodeURI(addressID),
type: "GET",
dataType: "json",
success:function(data) {
//this is the part that appends my table
$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// 2. Loop through all entries
var keys = ['id', 'title', 'price'];
data.forEach(function(row) {
var $row = $('<tr />');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$('#table tbody').append($row);
});
//
}
});
}else{
$('div.options').empty();
}
});
});
</script>
PS:与我的问题无关,只是为了避免不必要的问题 我正在使用laravel的问题,这就是为什么您在我的Ajax中看到
{{...}}
代码。
答案 0 :(得分:0)
我在forEach
之前和之后又添加了两行,并将数据限制为仅标题。
var keys = ['id', 'title', 'price'];
var keys = ['title'];
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
//added new row before forEach
$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row['id']+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
//added new row after forEach
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');
success:function(data) {
// $('div.options').empty();
$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th width="50" class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// 2. Loop through all entries
var keys = ['title'];
data.forEach(function(row) {
var $row = $('<tr />');
$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row['id']+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');
$('#table tbody').append($row);
});
}
希望它可以帮助别人。