我不能在Laravel中使用route :: post(错误419(未知状态))

时间:2017-09-16 06:18:01

标签: javascript php ajax laravel

我有一个Ajax代码,它使用type =“get”,但我想将类型更改为“post”

$.ajax({
    url:   '/crear',
    type:  'post',
    cache: 'false',
    contentType: 'false',
    processData: 'false',
    data:  {'nombre':Vnombre,'codigo':Vcodigo,'descripcion':Vdescripcion,'arrayCategorias':arrayCategoriasAux,'arrayColores':arrayColoresAux,'arrayTallas':arrayTallasAux}
}).done(function(data){

    window.location.replace("/almacen/producto");
});

我在web.php中改变了我的路线

Route::post('/crear', 'ProductoController@store');

但它没有用,我的浏览器中有错误419(未知状态)

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="csrf-token" content="{{ csrf_token() }}">

<script src="{{asset('js/jquery-3.2.1.js')}}"></script>
<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
我的控制器:

    public function store(ProductoFormRequest $request)
    {
        if ($request->ajax()) {

            if (!(empty($request->nombre)) && !(empty($request->codigo)) && !(empty($request->descripcion))) {

                # code...
                $producto              = new Producto;
                $producto->codigo      = $request->codigo;
                $producto->nombre      = $request->nombre;
                $producto->descripcion = $request->descripcion;
                $producto->stock       = '0';
                 $producto->estado = '1';
                $producto->save();
            }
        }
    }
我的要求

<?php

namespace sistema\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductoFormRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'codigo'      => 'required|max:45',
            'nombre'      => 'required|max:45',
            'descripcion' => 'max:45',
            'stock'       => 'max:11',
        ];
    }
}

只有我想将Files []和其他数组[]发送到我的控制器,如果有人有更好的主意请帮帮我

我的表格

<form onsubmit="FuncionGuardar();"  method="Post" enctype="multipart/form-data" class="form-horizontal" id="add_user_form">
{{csrf_field()}}
<div class="row">
	<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
		<label for="codigo"> Nombre</label>

		<input class="form-control" required value="{{old('nombre')}}" type="text" id="inNombre" name="nombre" placeholder="Nombre">
	</div>
	<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
		<label for="codigo"> Codigo</label>
		<input class="form-control" required value="{{old('codigo')}}" type="text" id="inCodigo" name="codigo" placeholder="Codigo">
	</div>
</div>
<div class="row">
	<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
		<label for="codigo"> Descripcion</label>
		<input class="form-control" required value="{{old('descripcion')}}" type="text" id="inDescripcion" name="descripcion" placeholder="Descripcion">
	</div>
</div>
<div class="row">
	<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
	<div class="form-group">
		<label>Categorias</label>
		 	<div class="input-group">
				<select id="CategoriasSelect" name="idt_categoria" class="form-control" >
					@foreach($categorias as $cat)
           				<option value="{{$cat->idt_categoria}}">{{$cat->nombre}}</option>
					@endforeach
				</select>
				<span class="input-group-btn">
        			<a class="btn btn-primary " href="#" role="button" onclick="CrearBotonCategorias()">Añadir</a>
      			</span>
			</div>
		<small class="text-muted" >*Clic en la Categoria para eliminarla</small>
		<br>
			<div class="alert alert-info" role="alert">
				<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
					<div class="btn-group mr-2" role="group" aria-label="First group" id="DivCategorias">
    				<!-- Botones de categorias agregados -->
  					</div>
				</div>

			</div>



	</div>
	</div>
	<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
	<div class="form-group">
		<label>Colores</label>
		 	<div class="input-group">
				<select id="ColoresSelect" name="idt_color" class="form-control" >
					@foreach($colores as $coloKey)
           				<option   value="{{$coloKey->idt_color}}" style="background-color:{{$coloKey->color}};">
           					{{$coloKey->nombre}}
           				</option>
					@endforeach
				</select>
				<span class="input-group-btn">
        			<a class="btn btn-primary " href="#" role="button" onclick="CrearBotonColores()">Añadir</a>
      			</span>
			</div>
		<small class="text-muted" >*Clic en el Color para eliminarlo</small>
		<br>
			<div class="alert " role="alert">
				<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
  					<div class="btn-group mr-2" role="group" aria-label="First group" id="DivColores">
    				<!-- Botones de categorias agregados -->
  					</div>
				</div>
			</div>


	</div>
	</div>
</div>
<div class="row">
		<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
	<div class="form-group">
		<label>Tallas</label>
		 	<div class="input-group">
				<select id="TallasSelect" name="idt_categoria" class="form-control" >
					@foreach($tallas as $tallaKey)
           				<option value="{{$tallaKey->idt_talla}}">{{$tallaKey->nombre}}</option>
					@endforeach
				</select>
				<span class="input-group-btn">
        			<a class="btn btn-primary " href="#" role="button" onclick="CrearBotonTallas()">Añadir</a>
      			</span>
			</div>
			<small class="text-muted" >*Clic en la Talla para eliminarla</small>
		<br>
			<div class="alert alert-warning" role="alert">
				<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
  					<div class="btn-group mr-2" role="group" aria-label="First group" id="DivTallas">
    				<!-- Botones de tallas agregados -->
  					</div>
				</div>
			</div>


	</div>
	</div>
		<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
	<div class="form-group">
		<label>Imagenes</label>
		 	<div class="input-group">
		 		<input type="file" id="Imagenes" class="filestyle" name="files[]" accept=".jpg, .jpeg, .png" data-btnClass="btn-primary" multiple>

				<output id="list"></output>
			</div>
		<br>
			<div class="alert alert-success" role="alert">
				<div class="btn-toolbar" role="toolbar" aria-label="Toolbar with button groups">
  					<div class="btn-group mr-2" role="group" aria-label="First group" id="DivImagenes">
    				<!-- Botones de categorias agregados -->
  					</div>
				</div>
			</div>


	</div>
	</div>
</div>

<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div>
		<div class="form-group">
			<input type="submit" class="btn btn-primary" value="Submit">
			<a class="btn btn-danger" href="javascript:window.history.back();" role="button">Cancelar</a>
		</div>

	</div>
</div>
</form>

1 个答案:

答案 0 :(得分:3)

示例ajax请求

$('#submit-signup').on("click", function (e) {

            e.preventDefault();
            var formDataValues = document.forms.namedItem("signup-form");
            var formValues = new FormData(formDataValues);


            $.ajax({
                type: 'POST',
                url: siteUrl + '/signup',
                processData: false,
                contentType: false,
                dataType: 'json',
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                data: formValues,

                success: function (data) {



                },
                error: function (data) {

                }
            });
        });

<强>更新 419错误,因为您没有在表单中添加令牌 在表单

中添加此行
  {{csrf_field()}}

更新2 添加表单令牌非常简单

 <form action="{{url('add-user')}}"  method="Post" enctype="multipart/form-data" class="form-horizontal" id="add_user_form">
            {{csrf_field()}}
            <div class="form-body">
                <h3 class="form-section">Person Info</h3>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label class="control-label col-md-3">First Name</label>
                            <div class="col-md-9">
                                <input type="text" name="first_name" id="first_name" class="form-control first_name"  placeholder="First Name">

                            </div>
                        </div>

        </form>