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

问题描述

这是我的Ajax代码:

Here is my ajax code:

$('select[id=currency-data]').change(function () {

    var currency_id =   $(this).val();

    $.ajax({
        url: "{{Route('exchange-rate')}}",
        type: 'POST',
        data: {currency_id: currency_id },
        success: function(data){
            $('#ex-rate').val(data);
        }
    });
});

查看:

        {!! Form::label('currency_id', 'Currency:', ['class' => 'control-label']) !!}
        {!! Form::Select('currency_id', $currency_data, Input::old('currency_id'), ['id'=>'currency-data','class' => 'form-control','required']) !!}

        {!! Form::label('exchange_rate', 'Exchange Rate:', ['class' => 'control-label']) !!}
        {!! Form::input('number','exchange_rate', Input::old('exchange_rate'), ['id'=>'ex-rate','class' => 'form-control','readonly','required']) !!}

运行此命令时,出现错误:VerifyCsrfToken.php中的TokenMismatchException..

when i run this,i get the error:TokenMismatchException in VerifyCsrfToken.php..

有人可以提供解决方案吗?

can someone give solution???

推荐答案

hi,如果您将js和视图文件分开,并且想要使用ajax提交表单,则不希望对任何HTML标记使用数据属性来添加csrf令牌,例如这个.

hi if you are keeping js and view file separate and want to use ajax to submit forms than use data attributes for any HTML tag in view to add csrf token like this.

<div id="toke" data-token="{!! csrf_token() !!}"></div>

现在您可以访问js文件中的令牌

now you can access token in js files

$.ajax({
    url: "{{Route('exchange-rate')}}",
    type: 'POST',
    data: data: {_token: $('#token').data('token'),currency_id: currency_id },
    success: function(data){
        $('#ex-rate').val(data);
    }
 });
});

第二个选项是创建隐藏的输入元素,并使用jquery表单序列化来获取表单数据

2nd Option is create hidden input element and use jquery form serialize to fetch form data

<form id="form-data" action="url" method = 'POST' />
{!! csrf_field() !!}

{!! Form::label('currency_id', 'Currency:', ['class' => 'control-label']) !!}
{!! Form::Select('currency_id', $currency_data, Input::old('currency_id'), ['id'=>'currency-data','class' => 'form-control','required']) !!}

{!! Form::label('exchange_rate', 'Exchange Rate:', ['class' => 'control-label']) !!}
{!! Form::input('number','exchange_rate', Input::old('exchange_rate'), ['id'=>'ex-rate','class' => 'form-control','readonly','required']) !!}

jquery

var form = $("#form-data");
$.ajax({
        url: form.attr( 'action' ),
        type: 'POST',
        data: form.serialize(),
        success: function(data){
            $('#ex-rate').val(data);
        }
     });
});

这篇关于在laravel 5中使用ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 02:50