我正在学习在 Laravel 上使用 ajax 进行实时搜索的教程,但在实现中出现错误:
GET http://localhost:8000/search?search=k 500(内部服务器错误)
我遵循本教程 3 次,但总是遇到相同的错误。我是这样修改的:
<!DOCTYPE html>
<html>
<head>
<meta name="_token" content="{{ csrf_token() }}">
<title>Live Search</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="panel panel-default">
<div class="panel-heading">
<h3>Products info </h3>
</div>
<div class="panel-body">
<div class="form-group">
<input type="text" class="form-controller" id="search" name="search">
<input type="hidden" name="_method" value="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</div>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$('#search').on('keyup',function() {
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
});
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
</body>
</html>
我的控制器:
public function search(Request $request)
{
if($request->ajax()) {
$output="";
$products=DB::table('products')->where('title','LIKE','%'.$request->search."%")->get();
if($products) {
foreach ($products as $key => $product) {
$output.='<tr>'.
'<td>'.$product->id.'</td>'.
'<td>'.$product->title.'</td>'.
'<td>'.$product->description.'</td>'.
'<td>'.$product->price.'</td>'.
'</tr>';
}
return Response($output);
}
}
}
我正在为 3 个不同的数据库尝试此代码,但总是得到相同的错误 500 。
你需要declare variable
在Jquery/Javascript
如下图所示:
var value=$(this).val();
并将其传递variable
如下ajax
:
data:{'search':value}
更改以上几行,它应该可以工作!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句