我认为这段代码有很多错误。我需要的是创建一个表单,做一个XHR提交给控制器,获取数据,发送到模型,检查验证,返回到控制器与验证的输出,然后发送到视图消息“错误或成功”
routes.php文件
Route::get('checkValidationEmail', 'HomeController@checkValidationEmail');
<?php
echo Form::open(array('url' => 'checkValidationEmail', 'class' => 'form_notify'));
echo Form::text('Email', Input::old('Email'), array('placeholder'=>'Email', 'class' => 'hg'));
echo Form::close()
?>
<a href="#" class="send_email"> Notify Me!</a>
好的,这很好,接下来,问题就开始了。
AJAX
<script>
$(function () {
$(".send_email").click(function () {
email = $('.hg').val();
$.ajax({
type: "POST",
url: 'checkValidationEmail', //what is the correct url?
data: {
email: email
}
}).done(function (msg) {
alert(msg);
});
});
});
</script>
500错误:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException","message":"","file":"C:\\VertrigoServ\\www\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php","line":1439}}
控制器
class HomeController extends BaseController {
public function checkValidationEmail() {
//how to get the data from form and pass to the model, more exactly validate($input)
if ($validation) {
return true;
}
else {
return 'incorrect email'; //how send this message to the view?
}
}
}
模型
class Home extends Eloquent {
protected $table = 'emails';
public function validate($input) {
//validations
}
}
答案 0 :(得分:5)
在您的路线中,您将checkValidationEmail
定义为GET
请求,并且从您的ajax,您尝试将此作为POST
请求进行访问。所以这将抛出MethodNotAllowedHttpException
。所以你必须改变你的路线,
Route::get('checkValidationEmail', 'HomeController@checkValidationEmail');
要,
Route::post('checkValidationEmail', 'HomeController@checkValidationEmail');
或者,
Route::any('checkValidationEmail', 'HomeController@checkValidationEmail');