weixin_33695450 2017-08-20 07:00 采纳率: 0%
浏览 122

Laravel中的Ajax POST请求

I'm sending value named text from my <script> tag that is in a .blade.php file to controller by using POST Ajax request. If I do not write $.post function then it gives me output of text value in console. BUT when I write this Ajax request to send data to controller value do not pass. In short, I want to pass value from View to Controller and I am unable to do that. I have tried all YouTube tutorials and previous Stack Overflow questions. I also visited Laracasts but problem is not solved. Am I doing something wrong? Please help. Thank you.

shopReq.blade.php:

{{csrf_field()}}
<script>
    $(document).ready(function(){
        $('.ourItem').click(function(event){
                var text=$(this).text();
                $('#addItem').val(text);
                 console.log(text);
                $.post('shopReq',{'text':text,'_token':$('input[name=_token]').val()}),function(data){
                    console.log(data);
                });
        });
    });
</script>

Web.php:

Route::post('shopReq','UserController@special');

Controller:

class UserController extends Controller
{   
    public function special(Request $request){
        $articles = DB::table('shoppingtrips')->get();
        echo"DONE";
  //      return $request->all();
    }
}
  • 写回答

2条回答 默认 最新

  • weixin_33681778 2017-08-20 07:06
    关注

    Try the below ajax syntax:

    $.ajax({
        url: 'your route',
        method: 'post',
        data: {
            key1: value1
            // you can send more such key value pair here
        },
    
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(response){
    
        }
    });
    

    Don't forget to add CSRF-TOKEN, otherwise you will get the 500 (Internal Server Error) as it is required with post request.

    评论

报告相同问题?

悬赏问题

  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决