du21064 2015-02-07 19:42
浏览 55
已采纳

使用jQuery和Laravel框架发布请求

I need to receive data from jQuery post request, think there is some error with routs or controller, here is my post request javascript code:

$.post('http://localhost:8000/ajax',
                {

                    task: "comment_insert",
                    userID: _userID,
                    comment: _comment,
                    name: _name,
                    userName: _userName
                }

                ).error(
                    function(data)
                    {
                      alert("Error: "+ data); 
                    }
                 )
                .success(
                    function( data )
                    {
                        comment_insert(jQuery.parseJSON( data ));
                      console.log("RESPOND TEXT:" + data);

                    }
                 );

     }

Also here is my routes for Laravel framework:

Route::post('ajax', 'AjaxController@index');

Controller:

class AjaxController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function index()
    {
             return view('ajax.ajax');

    }
}

my ajax.php script is into /resource/views/ajax/ajax.php Also if I put script into /public/ajax/ajax.php all works fine....I use Laravel 5... Please help

EDIT:

I found what is problem but don't know how to solve.

When I disable csrf protection from: kernel.php code work anyone know how to make code work with csrf protection enabled?

  • 写回答

2条回答 默认 最新

  • douyong1974 2015-02-07 20:27
    关注

    UPDATE: The problem is that the new CSRF-protection does not work with ajax-requests. Here is what you could do:

    In your master template add a new meta tag with the current token like this

     <meta name="csrf-token" content="{{ Session::token() }}"> 
    

    Then when sending your ajax call you add the token like this:

    $.post('http://localhost:8000/ajax',
        {
            '_token': $('meta[name=csrf-token]').attr('content'),
            task: 'comment_insert',
            userID: _userID,
            comment: _comment,
            name: _name,
            userName: _userName
        })
        .error(
            ...
         )
        .success(
            ...
         );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line