【发布时间】:2017-06-18 07:50:10
【问题描述】:
有人可以用一个完整的最小示例来解释 Laravel 5.3 中的 ajax post 方法吗? 我知道网络上有一些资源,但我错过了一个简洁、直接的最小示例。
【问题讨论】:
有人可以用一个完整的最小示例来解释 Laravel 5.3 中的 ajax post 方法吗? 我知道网络上有一些资源,但我错过了一个简洁、直接的最小示例。
【问题讨论】:
我假设你对模型-控制器-视图范式有基本的了解,对 Laravel 有基本的了解,对 JavaScript 和 JQuery(为了简单起见,我将使用它们)有基本的了解。
我们将创建一个编辑字段和一个发布到服务器的按钮。 (这适用于从 Laravel 5.0 到 5.6 的所有版本)
首先你需要添加路由到你的routes/web.php。为视图创建一条路由,就像您在普通视图中所知道的那样:
Route::get('ajax', function(){ return view('ajax'); });
您需要创建的第二条路由是处理 ajax 发布请求的路由。注意它使用的是 post 方法:
Route::post('/postajax','AjaxController@post');
在刚才创建的(第二条)路由中,调用了AjaxController中的Controller函数post。所以创建控制器
php artisan make:controller AjaxController
并在 app/Http/Controllers/AjaxController.php 添加包含以下行的函数 post:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller {
public function post(Request $request){
$response = array(
'status' => 'success',
'msg' => $request->message,
);
return response()->json($response);
}
}
函数准备好通过 Http 请求接收数据并返回 json 格式的响应(由状态“成功”和函数从请求中得到的消息组成)。
在第一步中我们定义了指向视图ajax的路由,所以现在创建视图ajax.blade.php。
<!DOCTYPE html>
<html>
<head>
<!-- load jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- provide the csrf token -->
<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>
$(document).ready(function(){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(".postbutton").click(function(){
$.ajax({
/* the route pointing to the post function */
url: '/postajax',
type: 'POST',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN, message:$(".getinfo").val()},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
$(".writeinfo").append(data.msg);
}
});
});
});
</script>
</head>
<body>
<input class="getinfo"></input>
<button class="postbutton">Post via ajax!</button>
<div class="writeinfo"></div>
</body>
</html>
如果您想知道这个 csrf 令牌有什么问题,请阅读https://laravel.com/docs/5.3/csrf
【讨论】: