【发布时间】:2017-06-15 09:56:53
【问题描述】:
我正在使用 jQuery ajax 将记录插入到表中。它工作正常并返回一条通知记录已成功插入的闪存消息。现在我的问题是在插入记录后我不知道如何重新加载我的表以便可以反映更改。
注意我在表格所在的同一页面上通过引导模式插入。
这是返回我的记录的控制器:
public function index()
{
//
$subjects = Subject::all();
return view('subjects.show', compact('subjects'));
}
记录返回后,我是这样显示的:
<table class="table table-responsive table-hover table-condensed table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Level</th>
<th colspan="2">Actions</th>
</tr>
</thead>
<tbody>
@foreach($subjects as $subject)
<tr>
<td>{{$subject->name}}</td>
<td>{{$subject->level}}</td>
<td>
<a data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a>
</td>
<td>
<a data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a>
</td>
</tr>
@endforeach
</tbody>
</table>
这是我插入记录的脚本:
$(document).on('submit', '#subject-form', function(event) {
event.preventDefault();
/* Act on the event */
var name = $('#name').val();
var level = $('#level').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: $("#subject-form").attr('action'),
data: {name: name, level: level},
success: function(response) {
console.log(response);
if (response.success) {
$.notify({
icon: 'glyphicon glyphicon-check',
message: response.success
},{
type: 'info',
timer: 4000,
offset: 20,
spacing: 10,
z_index: 1031,
delay: 5000,
placement: {
from: "bottom",
align: "right"
},
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
},
});
} else {
// display error
}
$('#subject-modal').modal('toggle');
}
});
这是插入记录并生成快速响应的控制器方法:
public function store(Request $request)
{
//
//return json_encode(request('name'));
$response = array();
if (Subject::create(request(['name', 'level']))) {
$response['success'] = '<b>'.request('name').'</b>'.' created successfully';
} else {
$response['fail'] ='Error creating subject: <b>'.request('name').'</b>'.'. Try again, if problem persist contact administrator';
}
return \Response::json($response);
}
我有什么方法可以完成这项工作吗?感谢反馈和建议。谢谢!!!
【问题讨论】:
-
为什么不在 JavaScript 中调用 window.location.reload() 呢?否则,您需要在浏览器中刷新 HTML 内容。 Ajax 也能够提供该内容。
-
@btl window.location.reload() 重新加载页面但不起作用将关闭我的对话框并显示我的 Flash 消息。如何刷新html内容?
-
发出 AJAX 请求并使用 return response()->json($reponse); 返回新数据。然后在成功回调中将数据附加到您的 HTML 文档中。
-
@btl 在我的控制器存储方法中,我确定应该这样做,但现在根据我所拥有的,我可以返回响应和 Flash 消息吗?
-
@btl 我目前只返回带有响应字段的闪存混乱。
标签: javascript php jquery ajax laravel