【问题标题】:How to pass token in ajax post request laravel?如何在ajax post请求laravel中传递令牌?
【发布时间】:2017-07-28 14:53:01
【问题描述】:

有人可以告诉我如何在 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中检查了其他问题但无法解决,让我们看看是否有人可以使用我的代码。 如果需要更多信息,请询问。 url函数有效!

我也试试

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

它只有在我放入中间件例外时才有效,但我认为这不是一个好主意。

【问题讨论】:

  • 你检查了你的页面并在那里找到了 csrf 令牌吗?在带有 _token 名称的输入中?
  • 它是@Sletheren

标签: javascript jquery ajax


【解决方案1】:

- 潜在修复 N°1:

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

 {{ csrf_field() }}

并把它直接放在&lt;form&gt;之后

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

- 潜在修复 N°2:

确保在您的 config/session.php 中 domain 的值为 null。

并从storage/framework/sessions/storage/framework/views/ 中删除缓存

- 潜在修复 N°3:

使用{!! csrf_token() !!} 而不是{{ csrf_token() }}

- 潜在修复 N°4:

如果在 linux 或 mac 上,请确保 Session 目录具有权限: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');

【讨论】:

  • 立即查看答案
  • 非常感谢!现在我出城了,当我来的时候,我会试试的!无论如何,我认为除了修复 nº6 之外,一切都已完成。让我们看看!
  • 当然,如果对你有用,别忘了点赞并将其标记为正确答案
  • 我认为问题出在我的 gulp 中,没有很好地编译 JS,而且我终于获得了文件夹和使用元数据的权限:) 谢谢伙计!
猜你喜欢
  • 2018-07-28
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多