如何在Laravel 5.3中使用Ajax [英] How to use ajax in laravel 5.3

查看:73
本文介绍了如何在Laravel 5.3中使用Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Laravel的新手,正在使用Laravel 5.3.我想创建一个文本字段,在该字段中它将自动建议一些数据,当我选择数据时,它将添加到数组中.我想将该数组发送到控制器以供进一步使用.为此

I am new to Laravel and am using Laravel 5.3. I want to make a text field where it will automatically suggest some data and when I select a data it will add it to an array. I want to send that array to a controller for further use. For this the

查看文件如下:

view file is as follows:

<head>
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
    <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $(document).ready(function() {
            var members = {!!  json_encode($member)  !!};
            console.log(members);
            var arr = [];
            $("#tags").autocomplete({
                source: members,
                select: function (event, ui) {
                    arr.push(ui);
                    console.log(arr);
                }
            });
            $("#submit").click(function(event){
                $.ajax({
                    type: "POST",
                    url: '/storeresearch',
                    data: {selectedMembers: arr},
                    success: function( msg ) {
                        console.log(msg);
                    }
                });
            });
        });
        </script>
</head>
<body>
<form id="hu" action="/storeresearch" method="POST">
    {!! csrf_field() !!}
    <label>Research Author</label>
    <input type="text" id="tags" name="researchsupervisor_1" value="">
    <input type="submit" name="submit" id="submit" class="btn btn-primary" value="Add">
</form>
</body>

我的控制器文件如下:

My Controller file is as follows:

public function store(Request $request){
        if($request->ajax())
        {
            $mem = $request->all();
            return response()->json($mem,200) ;
        }
        else{
            return "not found";
        } 

web.php如下:

And web.php is as followings:

Route::post('/storeresearch','ResearchController@store');

但是似乎没有ajax调用发生.在控制器中,它始终进入else部分.任何人都可以解决什么问题?

But it seems that there is no ajax call happening. In the controller it always enters the else section. What is the problem can anyone help?

推荐答案

我通过以下操作解决了这个问题

I solved this problem by doing following

$.ajax({
                type:'POST',
                url:'your url',
                data:{_token: "{{ csrf_token() }}"
                },
                success: function( msg ) {
                }
            });

这篇关于如何在Laravel 5.3中使用Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆