当我在文本框中输入值时,如何自动搜索数据,假设该值是固定的。像这样<input type="text" name="search" id="search" class="form-control" value="10310" />
那里的值是10310
,当我打开页面时,我想自动搜索该值。现在,我的搜索有一个ajax,并且运行良好。但是我的问题是,当我通过在文本框中输入值来打开页面时,无法自动搜索该值。
预期的输出-我想自动搜索文本框中包含的数据。
查看
<input type="text" name="search" id="search" class="form-control" value="10310" />
<div id="divContent">
</div>
这是我的 Ajax脚本
<script type="text/javascript">
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('admin.employeemaintenance.actualTime.actionActualTime') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('#divContent').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
});
</script>
我的控制器
function actionActualTime(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = DB::table('employeefms')
->where('last_name', 'like', '%'.$query.'%')
->orWhere('first_name', 'like', '%'.$query.'%')
->orWhere('employee_no', 'like', '%'.$query.'%')
->get();
}
else
{
$data = DB::table('employeefms')
->orderBy('last_name', 'desc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<div class="container">
<img height="50px" width="60px" src="/storage/employee_photos/'.$row->employee_photo.'" /><span class="d-none">'.$row->employee_photo.'</span><br><br>
<p><b>Employee No: </b></p><input type="text" class="form-control col-md-2" value='.$row->employee_no.'></input><br>
<p><b>Name: </b></p><input type="text" class="form-control col-md-3" value='.$row->last_name.'></input><br><hr>
</div>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
echo json_encode($data);
}
}
答案 0 :(得分:0)
页面加载时query
未定义。请尝试以下操作:
<script type="text/javascript">
$(document).ready(function(){
var query = $('#search').val();
fetch_customer_data(query);
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query);
});
function fetch_customer_data(query = '') {
$.ajax({
url:"{{ route('admin.employeemaintenance.actualTime.actionActualTime') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data) {
$('#divContent').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
});
</script>