【问题标题】:How to use Ajax in Laravel 8如何在 Laravel 8 中使用 Ajax
【发布时间】:2021-07-26 06:11:04
【问题描述】:

我尝试使用 laravel 的 Ajax,但找不到我想要的。

如何在 Laravel 中使用 ajax?

在 main.js 文件中...

$.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url : "{{ route('saveToken') }}",
        data : {'token' : token},
        type : 'POST',
        dataType : 'json',
        success : function(result){

            console.log("===== " + result + " =====");

        }
    });

在刀片模板中 ...

<body>
     <meta name="csrf-token" content="{{ csrf_token() }}">
     <div class="wrapper">
     @yield('content')
     <script src="{{ asset('assets/js/main.js') }}"></script>
     </div>                
</body>

php 文件

//web.php
Route::get('/saveToken', [FcmController::class, 'saveToken']);

// Fcm controller
public function saveToken(Request $request)
{
...

关于使用 ajax url //"{{ route('saveToken') }}"

~~~/%7B%7B%20route('saveToken')%20%7D%7D  404 not found

// '/saveToken'

405 not allowed

【问题讨论】:

  • 路由定义获取但在 ajax 中您尝试发布方法
  • 您正在使用 post 方法,但在路由上您将其添加为 get 方法
  • 找不到可能是因为helper route() 使用了命名路由,将-&gt;name('saveToken') 添加到路由中。
  • 你不能在 JavaScript 文件中使用 Laravel 助手/代码。

标签: php ajax laravel


【解决方案1】:

更换路线

Route::post('/saveToken', [FcmController::class, 'saveToken'])-&gt;name('saveToken');

改变你的 ajax

 $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url : "{{ url('saveToken') }}",
        data : {'token' : token},
        type : 'GET',
        dataType : 'json',
        success : function(result){

            console.log("===== " + result + " =====");

        }
    });

【讨论】:

    【解决方案2】:

    您在 url 中调用路由名称,因此您必须在 route 中添加路由名称。

    Route::get('/saveToken', [FcmController::class, 'saveToken']);
    

    替换为

    Route::post('/saveToken', [FcmController::class, 'saveToken'])->name('saveToken');
    

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 2019-06-20
      • 2021-04-30
      • 2021-03-24
      • 2021-06-10
      • 2013-07-05
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多