2019年4月21日 星期日

laravel ajax

*laravel ajax:

*view:
resources\views\message.blade.php

<html>
<head>
<title>Laravel Ajax</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
function getMessage(){
   $.ajax({
      type:'get',
      url:'getmsg',
      data:'_token = {{csrf_token()}}',
      success:function(data){
         $("#msg").html(data.msg);
      }
   });
}
</script>
</head>
<body>
   <div id="msg">xxxxxx</div>
   <p><button onclick="getMessage()">透過 Ajax 傳送訊息</button></p>
</body>
</html>

-------------------
*controller:

php artisan make:controller AjaxController

app\Http\Controllers\AjaxController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AjaxController extends Controller
{
    public function ajaxView(){
        return view('message');
    }

    public function ajaxData(){
        $msg="Ajax 您好 !!";
        return response()->json(['msg'=> $msg]);
    }
}

-------------------
*route:
routes\web.php

Route::get('ajax','AjaxController@ajaxView');
Route::get('getmsg','AjaxController@ajaxData');

-------------------
*參考資料:
https://www.yiibai.com/laravel/laravel_ajax.html


沒有留言:

張貼留言