【问题标题】:Try to using ajax in laravel but return 404尝试在 laravel 中使用 ajax 但返回 404
【发布时间】:2022-02-02 16:45:36
【问题描述】:

我尝试使用 ajax 通过 json 获取数据。

我的控制器:

public function getFreeDay(Reservation $reservation): JsonResponse
{
    //here will be other data, this is for test
    try {
        return response()->json([
            'status' => 'success'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => 'error',
            'message' => 'Wystąpił Błąd'
        ])->setStatusCode(500);
    }
}

路线:

Route::post('/rezerwacja/{reservation}', [ReservationController::class, 'getFreeDay'])->name('getFreeDay');

ajax:

    $("select#select-service").change(function () {
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            method: "GET",
            url: getFreeDay + $(this).val(),

            //data: {id: $(this).data('id')}
        })
            .done(function (data) {

                window.location.reload();
            })
            .fail(function (data) {
                console.log($(this).data('id'))
                console.log(data.responseJSON.message);
            });
});
const getFreeDay = "{{ url('rezerwacja')}}/";

HTML:

  <select class="form-select" id="select-service">
                <option  selected>Wybierz usługe</option>
                @foreach($services as $service)
                    <option value="{{$service->id}}">
                        {{$service->service_name}}
                    </option>
                @endforeach
            </select>

但每次,当我通过我的选择列表项运行 ajax 时,它都会返回 404。 我知道 url 和路由有问题,但我不知道是什么。

【问题讨论】:

  • 文档中有一个关于Generating URLs To Named Routes的部分
  • 在浏览器控制台中记录 javascript 生成的 url,看看这里需要调整什么。

标签: php jquery ajax laravel


【解决方案1】:

url 和 route(name) 不同,在你的 url 中你使用了“getFreeDay”,它被用作 {{route('getFreeDay')}}

$.ajax({
    type : 'POST',
    url : '{{ route("getFreeDay") }}',
    data : data
    dataType : 'json'
}).done(function(){})

【讨论】:

  • 那将缺少必需的参数reservation
猜你喜欢
  • 2018-03-05
  • 2021-12-16
  • 2018-12-26
  • 1970-01-01
  • 2020-05-25
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
相关资源
最近更新 更多