1 回答
TA贡献1775条经验 获得超11个赞
首先从blade开始(请查看评论):
@extends('layout')
@section('content')
<div class="row">
<table class="table table-hover table-striped table-dark" id="slugTb">
<thead>
<tr>
<th scope="col"><input type="checkbox" id="checkHead" class="selectall"></th>
<th scope="col">Id</th>
<th scope="col">Day</th>
<th scope="col">Title</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@endsection
@section('scripts')
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: "{{ route('test.action') }}",
method: 'GET',
data: {
'slug': '{{ $packageSlug }}',
'query': query
},
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
@endsection
您使用了已弃用的 jquery 方法,例如success check
最好使用这三个:done, fail,always
下一路线 web.php:
Route::get('action', ['as' => 'test.action', 'uses' => 'TestController@action']);
在您的情况下,最好使用Requestparams bag,以便您可以添加所需数量的参数。
下一个控制器:
function action(Request $request)
{
$total_row = 1;
$packageSlug = $request->get('slug'); //names that you set in ajax data tag: {'slug': '{{ $packageSlug }}','query': query}
$query = $request->get('query');
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
您应该从控制器返回一些内容,以便 Blade 可以显示数据并对其进行 json 编码,以便 js 可以解析它。因此return response()->json($data);
另一种方式:
路线:
Route::get('/action/{slug}/{query}',['as' => 'test.action', 'uses' => 'TestController@action']);
刀片脚本:
<script>
$(document).ready(function() {
var query = 'damnSon';
$.ajax({
url: 'action/{{ $packageSlug }}/' + query,
method: 'GET',
dataType: 'json',
})
.done(function(data) {
console.log(data) //use console.log to debug
$('#slugTb tbody').html(data.table_data); //set table id so that you don't miss the right one
})
.fail(function(err) {
console.log(err) //in case if error happens
})
.always(function() {
console.log( "complete" ); //result despite the response code
});
});
</script>
和控制器:
function action($slug, $query)
{
$total_row = 1;
$packageSlug = $slug;
$query = $query;
$output = '<tr>
<td align="center" colspan="1">' . $packageSlug . '</td>
<td align="center" colspan="1">' . $query .'</td>
</tr>';
$data = array(
'table_data' => $output,
'total_data' => $total_row
);
return response()->json($data);
}
不推荐,因为您在ajax请求中手动输入路由:url: 'action/{{ $packageSlug }}/' + query如果您的路由发生变化,您必须在js中更改它。
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报