使用适用于 Laravel 的完整通用示例扩展 @Chen-Tsu Lin 的答案:
首先,您的代码应该可以在没有任何 javascript 的情况下运行,因此您需要扩展已有的内容。
让路由监听 ajax 请求(发布或获取更适合您的):
Route::post('helpers/ajax',
array('as' => 'ajax', 'uses' => 'App\Controllers\AjaxController@someMethod')
);
使用 jQuery,您将停止表单提交的默认功能并将其发送到您的 ajax uri
$('#yourSubmitButton').on('click', function(e){
e.preventDefault(); // the form will not be submitted
//do whatever necessary to collect the data, or just serialize the form
var formdata = $('#yourForm').serialize();
//perhaps validate the data, if you need, and then send by ajax
$.ajax({
url:'helpers/ajax',
type:'POST', //or GET if you wish as long as its consistent with the route
data: formdata,
dataType:'json', //this is for the data you will receive from the controller
cache:false,
success:function(data){
//show the "mail send message and whatnot
},
error:function(jxhr){
//handle errors
} })
})
缺少的是控制器上的方法,用于接收发布数据、验证、处理和回显请求(很可能是一个 json_encoded 数组)。
更多内容取决于您的实施。