Laravel 发出带参数的 AJAX GET 请求的最佳方式
Laravel best way to make an AJAX GET request with parameters
路线:
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].
是的,但我仍然不知道我会选择哪个用户 select,所以我不能在那里放置参数...
解决方法 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
let tmpUrl = "{{ route('user', 0)}}";
tmpUrl = tmpUrl.substr(0, tmpUrl.length - 1) + id;
或
let tmpUrl = "{{ route('user', '---')}}";
tmpUrl = tmpUrl.replace('---', id);
你不能像你这样用路由传递参数。
url:"{{ route('user')}}"+id, //This is wrong way
正确的方法是:
var url = "{{route('user', ':id')}}";
url = url.replace(':id', id);
在 ajax 调用中使用上述 url
变量。
希望这会有所帮助。
路线:
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].
是的,但我仍然不知道我会选择哪个用户 select,所以我不能在那里放置参数...
解决方法 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
let tmpUrl = "{{ route('user', 0)}}";
tmpUrl = tmpUrl.substr(0, tmpUrl.length - 1) + id;
或
let tmpUrl = "{{ route('user', '---')}}";
tmpUrl = tmpUrl.replace('---', id);
你不能像你这样用路由传递参数。
url:"{{ route('user')}}"+id, //This is wrong way
正确的方法是:
var url = "{{route('user', ':id')}}";
url = url.replace(':id', id);
在 ajax 调用中使用上述 url
变量。
希望这会有所帮助。