【发布时间】:2015-07-18 08:36:08
【问题描述】:
我有一个订阅框:
我的目标是当用户输入电子邮件时,我想将其保存到我的数据库中。
我已经知道如何通过 Laravel 使用表单发布来实现这一点。
通过 Laravel 形成 POST
public function postSubscribe() {
// Validation
$validator = Validator::make( Input::only('subscribe_email'),
array(
'subscribe_email' => 'email|unique:subscribes,email',
)
);
if ($validator->fails()) {
return Redirect::to('/#footer')
->with('subscribe_error','This email is already subscribed to us.')
->withErrors($validator)->withInput();
}else{
$subscribe = new Subscribe;
$subscribe->email = Input::get('subscribe_email');
$subscribe->save();
return Redirect::to('/thank-you');
}
}
现在,我想使用 Ajax 调用来避免页面加载并了解有关 Ajax 的更多信息。这是我尝试过的:
表格
{!! Form::open(array('url' => '/subscribe', 'class' => 'subscribe-form', 'role' =>'form')) !!}
<div class="form-group col-lg-7 col-md-8 col-sm-8 col-lg-offset-1">
<label class="sr-only" for="mce-EMAIL">Email address</label>
<input type="email" name="subscribe_email" class="form-control" id="mce-EMAIL" placeholder="Enter email" required>
<!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
<div style="position: absolute; left: -5000px;"><input type="text" name="b_168a366a98d3248fbc35c0b67_73d49e0d23" value=""></div>
</div>
<div class="form-group col-lg-3 col-md-4 col-sm-4"><input type="submit" value="Subscribe" name="subscribe" id="subscribe" class="btn btn-primary btn-block"></div>
{!! Form::close() !!}
Ajax 调用
<script type="text/javascript">
$(document).ready(function(){
$('#subscribe').click(function(){
$.ajax({
url: '/subscribe',
type: "post",
data: {'subscribe_email':$('input[name=subscribe_email]').val(), '_token': $('input[name=_token]').val()},
dataType: 'JSON',
success: function (data) {
console.log(data);
});
});
});
</script>
控制器
public function postSubscribeAjax() {
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
die;
}
dd($data);
}
路线
Route::post('/subscribe','SubscribeController@postSubscribeAjax');
结果
我不断得到:
未定义变量:数据
这意味着我的Request::ajax() 不包含任何内容?这是为什么呢?
如何使用 Ajax 调用来实现这一点?
【问题讨论】:
标签: php jquery ajax laravel laravel-5