正如主题中提到的,当尝试使用 jQuery 和 ajax 提交表单时,我在 RouteCollection.php 中收到 MethodNotAllowedHttpException
我在我的routes.php文件中尝试了以下操作
Route::post('/send/', 'CommsController@send');
和
Route::patch('/send/', 'CommsController@send');
Controller
use App\Http\Controllers\Controller;
class CommsController extends Controller
{
protected function send(Request $request);
{
return response($request);
}
}
jQuery ajax
if ( isValid ) {
$( ".validation-summary" ).html( "Sending message..." );
var data = "";
data = "message_type=contact"
+ "&first_name=" + first_name.val()
+ "&last_name=" + last_name.val()
+ "&email=" + email.val()
+ "&message=" + message.val()
$.ajax({
type: "post",
url: "send",
data: data,
error: function( response ) {
$( ".validation-summary" ).removeClass( "success" );
$( ".validation-summary" ).addClass( "validation-summary error" );
$( ".validation-summary" ).html( "Error" );
},
success: function() {
$( ".validation-summary" ).html( "Message sent." );
}
});
return false;
} else {
return false;
}
谢谢。
最佳答案
在 Laravel 5.2 中,您需要在 web
中间件中设置路由,并且我假设您已经将 post
路由放置在中间件中:
Route::group(['middleware' => ['web']], function() {
Route::post('/send', 'YourController@methodName');
});
如果我在你的地方,我会做一些其他的事情,尽管与你的代码所做的类似。
jQuery
(function() {
// replace $('.btnSubmit') with whatever you want
$('.btnSubmit').click(function(e) {
var form = $('#yourFormId'),
postAction = form.attr('action'),
postData = form.serialize();
$.ajax({
type: 'POST',
url: postAction,
data: postData,
success: function(res) {
console.log(res);
},
error: function(res) {
console.log('Error:' + res);
}
});
return false;
});
})();
我做了什么:
- 将操作参数直接放置在表单中,而不是在 jQuery AJAX 中定义
- 序列化表单的输入值并发布相同的内容
- 使用自调用匿名函数
附注:
您正在重复 $('.validation-summary')
5 次。这意味着您违反了Principles of DRY这是不推荐的。解决方案:
var valSum = $('.validation-summary');
然后您可以在该代码段中使用它 n
次。
希望这对您有帮助。快乐编码。干杯。
关于jquery - 尝试使用 jQuery 和 ajax 提交表单时,我在 RouteCollection.php 中收到 MethodNotAllowedHttpException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34783685/