我已经体验到提交一个模式的形式,无需重新加载整个页面。我让用户将选项添加到下拉列表中,然后重新填充该下拉列表中的项目,而无需在添加项目后重新加载整个页面。
你可以有你的控制器处理过程中,可以通过调用的自定义路线JavaScript和返回JSON
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
随后的JavaScript
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
您可以查看完整的教程Creating new Dropdown Option Without Reloading the Page in Laravel 5
通过定期POST请求或通过AJAX向控制器发送表单与控制器相同。如果你的控制器和表单在没有AJAX的情况下工作,那么问题出现在JavaScript中,并且与Laravel控制器无关。 – ruuter
好的,但是假设您以常规方式发布给控制器,您如何向视图吐出JSON响应而不是重新加载页面?整个AJAX发布的目的不是为了防止重新加载? – Chriz74
你很容易吐出json返回response() - > json(['key'=>'value']);'。这将返回正确的响应与JSON正确的标题。重新加载或不重新加载页面全部通过JavaScript完成。您向控制器发送AJAX请求并获得JSON响应,然后您必须使用您自己的数据填充视图,并使用您需要的任何JS代码。 – ruuter