如何从Laravel中的Ajax调用中检索数据?

时间:2015-05-07 18:30:57

标签: php ajax laravel laravel-5

现在我收到了发布电子邮件的Ajax调用,我仍然在努力检索它,验证它并将其插入我的数据库。

这就是我所拥有的:

控制器

public function postSubscribe() {
    if(Request::ajax()) {
        $data = Input::all();
    }

    dd(json_decode($data));

    // 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');

    }
}

路线

Route::post('/subscribe','SubscribeController@postSubscribe');

既然发布了帖子请求,我无法在哪里看到dd(json_decode($data));?我做得对吗?请纠正我。

表格

{!! 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">

  <button type="button" name="subscribe" class="btn btn-primary btn-block" id="subscribe">Subscribe</button>

</div>

{!! Form::close() !!}

的Ajax

<script type="text/javascript">
  $(document).ready(function(){
    $('#subscribe').click(function(e){
     e.preventDefault();

     $.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);
      } // this is good

    });
   });
  });

</script>

成功发布数据

enter image description here

问题

如何在将来自行调试类似的东西? 在PHP Laravel中从Ajax调用中检索数据的最实用的方法是什么?

1 个答案:

答案 0 :(得分:0)

感谢@Pawel Bieszczad

更改:dd(json_decode($data));

至:dd(json_encode($data));

并打开控制台&gt; 网络标签&gt;的响应

现在我看到了我的回应。

"{"subscribe_email":"bheng@outlook.com","_token":"S3lWmNn6gkkHrYY6nPmupCtrlRqWF6au7b0Mywy7"}"