本文介绍了laravel 5.2有效的ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在Laravel 5.2中检查请求是否为有效的Ajax请求.在codeigniter中,我们可以像$ this-> input-> is_ajax_request()一样检查它. Laravel 5.2是否具有类似的功能?

How can we check in Laravel 5.2 if a request is a valid ajax request. In codeigniter ,we could check it like $this->input->is_ajax_request(). Does, Laravel 5.2 has something similar?

此外,我想知道我们如何验证对csrf令牌的请求.如果我让网页通过网络"中间件进行渲染并生成csrf令牌,然后将此令牌作为ajax请求参数传递,就可以了吗? Laravel会负责验证令牌吗?还是有其他解决方法?

Also, I would like to know that how can we validate a request for csrf token. Is it fine if I let my webpage render through the 'web' middleware generating a csrf token and then pass this token as ajax request parameter? Would Laravel take care of validating the token or is there an alternate way around this?

我已经检查了laravel 5.2文档,并且由于这是我第一次处理laravel框架,因此该文档似乎假定读者已经熟悉该框架的早期版本.对于像我这样的新手来说,这简直是不知所措.

I have checked the laravel 5.2 documentation, and since this is the first time I am dealing with laravel framework, it seems like the documentation assumes that the reader already has a familiarity with earlier versions of the framework. To a new comer like me this is little overwhelming.

先谢谢了.如果您需要我提供更多信息,请告诉我.

Thanks in advance. Please let me know if you need more inputs from me.

Prakhar

推荐答案

我认为这可能有助于您理解将Laravel与AJAX结合使用的基本方法.

I think this may help you to undestand a very basic way of using AJAX with Laravel.

这是一段非常古老的代码,但是可以使用jajajaja

It's a really old piece of code, but it works jajajaja

控制器端:

/**
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function getRamos(Request $request)
{
    $check = Ramo::find($request->input('ramo'));
    $subramos = Subramo::where('ramo_id', $check->id)->get(['nombre_subramo']);
    if($request->ajax()){
        return response()->json([
            'subramos' => $subramos
        ]);
    }
}

在前面:

<script>
    $(document).ready(function(){
        $('#ramo').change(function(){
            var ramo, token, url, data;
            token = $('input[name=_token]').val();
            ramo = $('#ramo').val();
            url = '{{route('getRamos')}}';
            data = {ramo: ramo};
            $('#subramos').empty();
            $.ajax({
                url: url,
                headers: {'X-CSRF-TOKEN': token},
                data: data,
                type: 'POST',
                datatype: 'JSON',
                success: function (resp) {
                    $.each(resp.subramos, function (key, value) {
                        $('#subramos').append('<option>'+ value.nombre_subramo +'</option>');
                    });
                }
            });
        });
    });
</script>

将"#ramo"视为选择输入,并使用style/html包,其中令牌作为隐藏输入传递.

Considering "#ramo" as a select input and in use of the style / html package where the token is passed as a hidden input.

这篇关于laravel 5.2有效的ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:28
查看更多