Ajax 发布到 Laravel 4 中的路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19521440/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:35:22  来源:igfitidea点击:

Ajax post to route in Laravel 4

phpajaxlaravellaravel-4

提问by Pars

I am going to send some data to current pageusing ajax to insert something in database.
Assume this ajax code:

我将使用 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>');
    });
});

This piece of code sends data to URL / and it works well. but I want to send it to a Route.Namewhich route sends it to a controller@action.
is there anyway or workaround to do this?

这段代码将数据发送到 URL / 并且运行良好。但我想将它发送到一个Route.Name路由将它发送到一个控制器@动作。
有没有办法或解决方法来做到这一点?

回答by devo

In your route,

在你的路线上,

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

In HomeController,

在 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
  }
}

And finally the script,

最后是剧本,

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

回答by Damien Pirsy

You could change

你可以改变

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

to

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

Your route should then be:

你的路线应该是:

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

Note the use of the named routesinstead of building the url using URL::to('controller/action')

请注意使用命名路由,而不是使用URL::to('controller/action')