这个 View 有一个调用 javascript 函数的链接
@extends('layouts.main')
@section('content')
<table class="table">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Opción</th>
</tr>
@foreach ($tasks as $task)
<tr>
<td>{{$task->id}}</td>
<td>{{$task->name}}</td>
<td><a href="javascript:void(0)" onclick="eliminar({{$task->id}})" class="btn btn-danger">Eliminar</a></td>
</tr>
@endforeach
</table>
@stop
这是javascript代码
function eliminar(id){
$.ajax({
type: "DELETE",
url: "task/"+id,
success: function (data) {
console.log(data);
},
error: function (data) {
alert('Error:', data);
}
});
}
通过 ajax 调用,我想调用 Controller 的销毁方法
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Task;
class TaskController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$tasks = Task::all();
return view('mainview',['tasks' => $tasks]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
return "destroy";
}
}
但是当我点击链接时出现这个错误:
TokenMismatchException in VerifyCsrfToken.php line 67
我是 Laravel 的新手,但我认为 csrf 是用于表单的。
最佳答案
您应该将 csrf_field
添加到您的主 Blade :
{{ csrf_field() }}
然后将_token
添加到您的请求中:
var _token = $('input[name="_token"]').val();
function eliminar(id){
$.ajax({
type: "DELETE",
url: "task/"+id,
data: { _token : _token },
success: function (data) {
console.log(data);
},
error: function (data) {
alert('Error:', data);
}
});
}
或者您可以在 ajaxSetup
中添加一次,它会影响对 $.ajax
或基于 Ajax 的衍生产品(例如 $.get( )
:
$.ajaxSetup(
{
headers:
{
'X-CSRF-Token': $('input[name="_token"]').val()
}
});
看看 CSRF Protection .
希望这对您有所帮助。
关于javascript - 使用 ajax 在 laravel 上的 VerifyCsrfToken.php 第 67 行中的 TokenMismatchException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37663432/