有人可以用Laravel 5.3中的ajax post方法解释一个完整的最小例子吗? 我知道网上有一些资源,但我想念一个简洁,直截了当的最小例子。
答案 0 :(得分:58)
我认为您对模型控制器视图范例有基本的了解,对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格式的响应(包含状态'success'和函数从请求中获得的消息)。
在第一步中,我们定义了指向视图 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-token的问题是什么,请阅读https://laravel.com/docs/5.3/csrf