我对ajax和json相当陌生,非常感谢您的帮助。 我正在对Laravel控制器进行Ajax调用,以从称为“主题”的数据库表中返回一些字段,并将其显示在Laravel视图的数据表中。问题是,当我打开视图时,看到的是JSON而不是数据表。
以下是查看主题/索引中返回的内容:
{"draw":0,"recordsTotal":8,"recordsFiltered":8,"data":[{"id":"1","name":"Biology"},{"id":"3","name":"English Language"},{"id":"4","name":"Physics"},{"id":"5","name":"Chemistry"},{"id":"6","name":"Mathematics"},{"id":"7","name":"Mathematics"},{"id":"8","name":"English Language"},{"id":"9","name":"French"}],"queries":[{"query":"select count(*) as aggregate from (select '1' as `row_count` from `subjects`) count_row_table","bindings":[],"time":4.65},{"query":"select `id`, `name` from `subjects`","bindings":[],"time":0.41}],"input":[]}
这是视图/ subjects / index中的HTML
<table id="subjects_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
这是Laravel控制器中的代码:
class SubjectsController extends Controller
{
public function index()
{
$subjects = Subject::select('id', 'name');
return Datatables::of($subjects)->make(true);
}
}
以下是进行Ajax调用的代码:
$('#subjects_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": "{{route('subjects.index')}}",
"columns":[
{"data": "id"},
{"data": "name"}
]
});
以下是web.php中的路由定义:
Route::get('subjects/', 'SubjectsController@index')->name('subjects.index');
我们将不胜感激
答案 0 :(得分:0)
您应该尝试以下操作:
路线
Route::get('subjects', 'SubjectsController@index')->name('subjects.index');
Route::get('getsubjects', 'SubjectsController@getSubjects')->name('subjects.get');
SubjectsController
class SubjectsController extends Controller
{
public function index()
{
return view('subjects.index');
$subjects = Subject::select('id', 'name');
return Datatables::of($subjects)->make(true);
}
public function getSubjects()
{
return \DataTables::of(Subject::query())->make(true);
}
}
查看
<table id="subjects_table" class="table table-bordered" style="width:100%">
<thead>
<tr>
<th>Id</th>
<th>Subject</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#subjects_table').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('subjects.get') }}',
columns: [
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
]
});
});
</script>