如何在ajax post request laravel中传递令牌?

时间:2017-07-28 14:53:01

标签: javascript jquery ajax

有人可以告诉我如何在laravel的ajax中传递一个表单的所有数据吗?

我将举一个例子,我无法通过它导致令牌遗失。

Javascript代码:

$(document).ready(function(){

    $("#buttoncreate").click(function(){
        $("#listall").hide();
        $("#form1").fadeIn(1000);

    });

    $("#createprojectsubmit").click(function(){
        $("#myForm").submit();
    });

    $("#myForm").submit(function(e){
        e.preventDefault();
        $.ajax({
            url:'/admin/projects/postUpload',
            type:'post',
            data:$('#myForm').serializeArray(),
            success: function(){
                $("#form1").fadeOut(1000);
                $("#form2").fadeIn(1000);
            }
        });
    });
});

刀片代码:

@extends('cms.public.layouts.default')
@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}">

<div class="col-md-10">
    <h3 style="letter-spacing:40px;text-align:center;color:f15d5e;">PROYECTOS</h3>
</div>

<div id="listall"> <!-- DIV TO LIST ALL THE PROJECTS START HERE -->
        <div class="col-md-2" style="padding:20px;">
          <button type="button" id="buttoncreate" class="btn btn-danger">Crear Proyecto</button>

        </div>
                      <table class="table">
                  <thead style="color:white">
                    <tr>
                      <th>Id</th>
                      <th>Slug</th>
                      <th>Order</th>
                      <th>Public</th>
                      <th>Path header</th>
                      <th>Path home</th>
                      <th>Fecha creación</th>
                      <th>Fecha ultima actualización</th>
                      <th><span class="glyphicon glyphicon-cog"></span></th>
                    </tr>
                  </thead>
                  <tbody style="color:white">
                  @foreach ($projects as $key => $project)
                    <tr>
                      <th>{{$project->id}}</th>
                      <td>{{$project->slug}}</td>
                      <td>{{$project->order}}</td>
                      <td>{{$project->public}}</td>
                      <td>{{$project->pathheader}}</td>
                      <td>{{$project->pathhome}}</td>
                      <td>{{ date('M j, Y', strtotime($project->created_at))}}</td>
                      <td>{{ date('M j, Y', strtotime($project->updated_at))}}</td>
                      <td><a href="{{ route('admin.projects.show', $project->id)}}" class="btn btn-info btn-sm">View</a> <a href="{{ route('admin.project.edit', $project->id)}}" class="btn btn-success btn-sm">Edit</a>
                  @endforeach
                    </tr>
                  </tbody>
                </table>
  <br><br>
</div>  <!-- DIV TO LIST ALL THE PROJECTS END HERE -->

<div id="form1" style="display:none;" class="col-md-8"> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 START HERE-->
    <div>
    <h3>Crear nuevo proyecto</h3>
    </div>
    <div id="formcreateproject">
        <form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data" id="myForm" name="myForm">
        {{ csrf_field() }}
          <div class="form-group">
            <label name="title">Slug:</label>
            <input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
            <label name="order">Order:</label>
            <input type="number" id="order" name="order" class="form-control form-control-sm">
            <label name="public">Public:</label>
            <input type="number" id="public" name="public" class="form-control form-control-sm">
             <label name="body">Header</label>
            <input type="file" name="pathheader" id="pathheader"  class="form-control-file" aria-describedby="fileHelp"><br>
            <label name="body">Home</label>
            <input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>

            <input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
            <input type="hidden" name="_token" value="{{ Session::token() }}">
            <br><br><br>

          </div>
        </form>

      </div>
</div> <!-- DIV TO SHOW THE CREATE PROJECT FORM 1 END HERE-->

<div id="form2" style="display:none;" class="col-md-6">
<div class="col-md-">
    <h3>Crear nuevo proyecto</h3>
    </div>
      <form method="POST" action="{{ route('admin.projects.store') }}" enctype="multipart/form-data">
          <div class="form-group">
            <label name="title">Slug:</label>
            <input type="text" id="slug" name="slug" placeholder="ejemplo-de-slug" class="form-control form-control-sm">
            <label name="order">Order:</label>
            <input type="number" id="order" name="order" class="form-control form-control-sm">
            <label name="public">Public:</label>
            <input type="number" id="public" name="public" class="form-control form-control-sm">
             <label name="body">Header</label>
            <input type="file" name="pathheader" id="pathheader"  class="form-control-file" aria-describedby="fileHelp"><br>
            <label name="body">Home</label>
            <input type="file" name="pathhome" id="pathhome" class="form-control-file" aria-describedby="fileHelp"><br>

            <input type="submit" value="Crear Proyecto" id="createprojectsubmit" class="btn btn-danger btn-md">
            <input type="hidden" name="_token" value="{{ Session::token() }}">
            <br><br><br>

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

</div>
@stop

任何帮助都会很感激!我在stackoverflow中检查了其他问题,但无法修复它,让我们看看我的代码是否可以。 如果需要更多信息,请询问。 网址功能有效!

我也试试

  

https://laravel.com/docs/5.4/csrf#csrf-x-csrf-token

只有在我放入中间件的例外情况下它才有用,但我认为这不是一个好主意。

1 个答案:

答案 0 :(得分:2)

- 潜在修复N°1:

在您的第一个表单中,删除

 {{ csrf_field() }}

并将其直接放在<form>

之后
<input type="hidden" name="_token" value="{{ Session::token() }}">

- 潜在修复N°2:

确保 config / session.php 内的域值为null。

并从storage/framework/sessions/storage/framework/views/

删除缓存

- 潜在修复N°3:

使用{!! csrf_token() !!}代替{{ csrf_token() }}

- 潜在修复N°4:

如果在linux或mac上,请确保Session dir具有权限:sudo chmod -R 777 Storage将完成此任务。

- 潜在修复N°5:

添加到头部的主布局:

<meta name="csrf-token" content="{{ csrf_token() }}">

并配置所有ajax请求以使用CSRF令牌,这样您无需每次在提交的表单中附加它 您可以添加为主布局中的第一个标记。

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

- 潜在修复N°6:

如果全部失败,则通过将这些行添加到VerifyCsrfToken.php中间件文件中来允许访问控制。

$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');