【问题标题】:Ajax post to route in Laravel 4Ajax 发布到 Laravel 4 中的路由
【发布时间】:2013-10-31 12:49:12
【问题描述】:

我将使用 ajax 将一些数据发送到 当前页面 以在数据库中插入一些内容。
假设这个 ajax 代码:

$('#newPost :submit').click(function(e){
            var BASE = 'http://localhost/project/public/';
    e.preventDefault();
    $.post(BASE, {
        'message' : $('#newPost textarea.message').val()
        }, function(data) {
        $('#content').prepend('<p>' + data + '</p>');
    });
});

这段代码将数据发送到 URL / 并且运行良好。但我想将其发送到 Route.Name,该路由将其发送到 controller@action。
有什么办法或解决方法吗?

【问题讨论】:

    标签: php ajax laravel laravel-4


    【解决方案1】:

    在你的路线中,

    Route::get('data', array('uses' => 'HomeController@store'));
    

    在 HomeController 中,

    public function store() {
      $input = Input::all(); // form data
      // validation rules
      $rules = array(
        'email'   => 'required|email', 
        'name'    => 'required', 
      ); 
    
      $validator = Validator::make($input, $rules); // validate
      // error handling
      if($validator->fails()) {
        if(Request::ajax()) {   // it's an ajax request                 
          $response = array(
             'response'  =>  'error',
             'errors'    =>  $validator->errors()->toArray()
          );                
        } else { // it's an http request
           return Redirect::intended('data')
                      ->withInput()
                      ->withErrors($validator);
        }
      } else { // validated
         // save data
      }
    }
    

    最后是脚本

    var root_url = "<?php echo Request::root(); ?>/"; // put this in php file
    $('#newPost :submit').click(function(e){
        var BASE = root_url + 'data';
        e.preventDefault();
        $.post(BASE, {
            'message' : $('#newPost textarea.message').val()
            }, function(data) {
            $('#content').prepend('<p>' + data + '</p>');
        });
    });
    

    【讨论】:

    • 所以我需要使用 Request::ajax() 来检查它是否是一个ajax请求。在常规使用中,为了发回我使用$errors-&gt;has 的错误,我如何在ajax 提交后访问$errors?!
    【解决方案2】:

    你可以改变

    var BASE = 'http://localhost/project/public/';
    

    var BASE = '<php echo URL::route("name");?>'
    

    你的路线应该是:

    Route::post('action', array('as' => 'name', 'uses' => 'HomeController@action'));
    

    注意使用named routes,而不是使用URL::to('controller/action')构建url

    【讨论】:

    • 这是 Laravel 4 的语法吗?
    • 所以我需要使用 Request::ajax() 来检查它是否是一个ajax请求。在常规使用中,为了发回我使用 $errors->has 的错误,我如何在 ajax 提交后访问 $errors?!
    • 如果您有错误或没有错误,您可以发送不同的回复
    猜你喜欢
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    相关资源
    最近更新 更多