json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)
<html> <head> <title>Laravel Ajax示例</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script> function getMessage(){ $.ajax({ type:'get', url:'/getmsg', data:'_token = <?php echo csrf_token() ?>', success:function(data){ $("#msg").html(data.msg); } }); } </script> </head> <body> <div id = 'msg'>这条消息将会使用Ajax来替换. 点击下面的按钮来替换此消息.</div> <?php echo Form::button('替换消息',['onClick'=>'getMessage()']); ?> </body> </html>
php artisan make:controller AjaxController
app/Http/Controllers/AjaxController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class AjaxController extends Controller { public function index(){ $msg = "这是一条简单的消息."; return response()->json(array('msg'=> $msg), 200); } }
app/Http/routes.php
Route::get('ajax',function(){ return view('message'); }); Route::get('/getmsg','AjaxController@index');
http://localhost:8000/ajax