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