dongweihuan8610 2015-06-05 10:26
浏览 153
已采纳

在Laravel中使用ajax发布表单

I know this question has been out there many times, however I am unable to get through this.

Here is my route:

Route::post('/masters/board/edit', 'MastersController@editBoard');

My Controller:

public function editBoard() {
        $board = Board::findOrFail(Input::get('id'));
        $board->nick_name        = Input::get('nick_name');
        $board->board_name        = Input::get('board');
        $board->type                        = Input::get('type');
        $board->save();

        return Redirect::action('MastersController@getBoards');
    }

My JS:

$("#edit_form").submit(function(e) {
    e.preventDefault();

    var type = "#edit_form";

    var formData = {
          id : $(type + " #id").val(),
          nick_name : $(type + " #nick_name").val(),
          name : $(type + " #board").val()
      }

    $.ajax({
      type: "POST",
      url: "masters/board/edit",
      data: formData,
      success: function(data) {
        console.log(data);
      }
    });
  });
});

This is throwing an error:

[Error] Failed to load resource: the server responded with a status of 500 (Internal Server Error) (edit, line 0)

Can anyone see a reason why?

  • 写回答

1条回答 默认 最新

  • douchengjue9892 2015-06-05 12:28
    关注

    Add a meta tag with the csrf_token.

    <meta name="_token" content="{{ csrf_token() }}" />
    

    And add that token to your data.

    var formData = {
      id : $(type + " #id").val(),
      nick_name : $(type + " #nick_name").val(),
      name : $(type + " #board").val()
      _token: $('meta[name="_token"]').attr('content')
    }
    

    If you are going to perform lot of post requests try the following. Use the following script to setup your ajax requests with the csrf token.

    $(function() {
      $.ajaxSetup({
        headers: {
          'X-CSRF-Token': $('meta[name="_token"]').attr('content')
        }
      });
    });
    

    If you are using laravel 5 this should work out of the box. If not you need to edit your app/filters.php file.

    Replace the csrf filter with the following.

    Route::filter('csrf', function() {
        $token = Request::ajax() ? Request::header('X-CSRF-Token') : Input::get('_token');
        if (Session::token() != $token)
            throw new Illuminate\Session\TokenMismatchException;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献