【问题标题】:Laravel best way to make an AJAX GET request with parametersLaravel 使用参数发出 AJAX GET 请求的最佳方法
【发布时间】:2021-06-12 21:06:38
【问题描述】:

路线:

Route::get('/user/{id}', "UserController@get")->name('user');//Get all users is not allowed.

表格:

<form>
<select id="selected_user">
<option value="1">Bob</option>
<option value="2">Alice</option>
</select>
<button id="get_user">Query</button>
</form>

AJAX:

$.ajax({
  url: "{{ route('user')}}"+id,
  type: "GET",
  data: null,
  dataType: 'json':
}).done(function(response){
  console.log(response);
});

你会得到什么: development.ERROR: Missing required parameters for [Route: user] [URI: user/{id}] [Missing parameters: id].

是的,但我仍然不知道我会选择哪个用户,所以我不能在那里设置参数......

解决方法 1:

POST Request (But I am not POST ing anything?)

AJAX 中的解决方法 2:

let id = getHTMLId();
url: {{ URL::to('/'); }}+"/user/"+id;//I will have to update all AJAX requests if there is a change to URL so it is now: users/get/{id}

解决方法 3(我不知道这是否可能):

Route::get('/user/{id?}', "UserController@get")->name('user');//Optional parameters, but the application should not be allowing a request to /users/ alone.

来自 Laravel 的预期方法

URL::routeWithoutParams('user');//其中user是命名路由

有没有合适的方法来做一个简单的 GET 请求?

我没有找到任何信息,所有示例似乎都读取了整个数据,例如 users/getall

【问题讨论】:

    标签: ajax laravel get request


    【解决方案1】:

    你不能像你正在做的那样用路由传递参数。

    url:"{{ route('user')}}"+id, //This is wrong way
    

    正确的做法是:

    var url = "{{route('user', ':id')}}";
    url = url.replace(':id', id);
    

    将上述url 变量与ajax 调用一起使用。

    希望这会有用。

    【讨论】:

      【解决方案2】:
      let tmpUrl = "{{ route('user', 0)}}";
      tmpUrl = tmpUrl.substr(0, tmpUrl.length - 1) + id;
      

      let tmpUrl = "{{ route('user', '---')}}";
      tmpUrl = tmpUrl.replace('---', id);
      

      【讨论】:

        猜你喜欢
        • 2020-12-07
        • 2020-11-23
        • 1970-01-01
        • 1970-01-01
        • 2017-09-12
        • 1970-01-01
        • 1970-01-01
        • 2019-08-06
        • 2018-04-23
        相关资源
        最近更新 更多