Laravel - Ajax



Ajax(非同步 JavaScript 和 XML)是一套用於建立非同步 Web 應用程式的 Web 開發技術,利用了客戶端使用的多種 Web 技術。在檢視檔案中匯入 jquery 庫以使用 jquery 的 ajax 函式,這些函式將用於使用 ajax 從伺服器傳送和接收資料。在伺服器端,您可以使用 response() 函式向客戶端傳送響應,並使用 json() 函式將響應傳送為 JSON 格式。

json() 函式語法

json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)

示例

步驟 1 - 建立一個名為 resources/views/message.php 的檢視檔案,並將以下程式碼複製到該檔案中。

<html>
   <head>
      <title>Ajax Example</title>
      
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
      
      <script>
         function getMessage() {
            $.ajax({
               type:'POST',
               url:'/getmsg',
               data:'_token = <?php echo csrf_token() ?>',
               success:function(data) {
                  $("#msg").html(data.msg);
               }
            });
         }
      </script>
   </head>
   
   <body>
      <div id = 'msg'>This message will be replaced using Ajax. 
         Click the button to replace the message.</div>
      <?php
         echo Form::button('Replace Message',['onClick'=>'getMessage()']);
      ?>
   </body>

</html>

步驟 2 - 透過執行以下命令建立一個名為 AjaxController 的控制器。

php artisan make:controller AjaxController --plain

步驟 3 - 成功執行後,您將收到以下輸出 -

AjaxController

步驟 4 - 將以下程式碼複製到

app/Http/Controllers/AjaxController.php 檔案中。

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 = "This is a simple message.";
      return response()->json(array('msg'=> $msg), 200);
   }
}

步驟 5 - 在 app/Http/routes.php 中新增以下行。

app/Http/routes.php

Route::get('ajax',function() {
   return view('message');
});
Route::post('/getmsg','AjaxController@index');

步驟 6 - 訪問以下 URL 以測試 Ajax 功能。

https://:8000/ajax

步驟 7 - 您將被重定向到一個頁面,您將在其中看到如下面的圖片所示的訊息。

Replace Message

步驟 8 - 點選按鈕後,輸出將如下圖所示。

Simple Message
廣告

© . All rights reserved.