source

Larabel 5.3에서의 ajax POST 최소 동작 예

bestscript 2023. 2. 22. 22:31

Larabel 5.3에서의 ajax POST 최소 동작 예

Larabel 5.3의 ajax 포스트 방법을 풀워킹 최소 예시로 설명해 주시겠습니까?웹에 몇 가지 리소스가 있다는 것은 알지만 간결하고 간단한 최소한의 예는 놓치고 있습니다.

모델컨트롤러뷰패러다임,라라벨의기본적이해,JavaScript와JQuery의기본적이해(간단함을위해사용합니다)라고생각합니다.

편집 필드와 서버에 투고하는 버튼을 작성합니다.(이는 Larabel 5.0에서 5.6까지의 모든 버전에서 유효합니다.)

1. 루트

처음에 루트/web.php에 루트를 추가해야 합니다.일반 뷰에서 알 수 있는 것처럼 뷰에 대해 하나의 경로를 작성합니다.

Route::get('ajax', function(){ return view('ajax'); });

작성해야 할 두 번째 경로는 Ajax 포스트 요구를 처리하는 루트입니다.Post 메서드를 사용하고 있는 것에 주의해 주세요.

Route::post('/postajax','AjaxController@post');

2. 컨트롤러의 기능

방금 작성한 (두 번째) 루트에서는 AjaxController의 Controller 함수 포스트가 호출됩니다.컨트롤러의 작성

php artisan make:controller AjaxController

앱/Http/Controllers/AjaxController에 있습니다.php는 다음 행을 포함하는 함수 게시물을 추가합니다.

<?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'와 함수가 요청에서 얻은 메시지로 구성됨)을 반환합니다.

3. 뷰

첫 번째 단계에서는 에이잭스를 가리키는 루트를 정의했습니다.그러면 뷰 에이잭스.블레이드를 만듭니다.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-timeout에 무슨 문제가 있는지 궁금하신 경우 https://laravel.com/docs/5.3/csrf를 참조하십시오.

언급URL : https://stackoverflow.com/questions/41981922/minimum-working-example-for-ajax-post-in-laravel-5-3