如何在 Laravel 中生成具有 placeholder/replaceable 值的路由以便在运行时在 JS 中使用?
How can I generate a route in Laravel with a placeholder/replaceable value for use in JS at runtime?
我有一条路线 returns post 数据在 JSON:
Route::get('posts/{post}/data', 'PostController@getData')->name('data.post');
前面JS调用:
<a href="#" data-post-id="{{ $post->id }}" class="post-links">{{ $post->title }}</a>
点击是这样绑定的:
$(".post-links").click(function() {
var postId = $(this).data('post-id');
$.get( "{{ route('data.post') }}" + postId, function(data) {
// process the data...
});
});
这里的问题是 get
的 URL 必须在前端生成,具体取决于点击了哪个 link,但是 Laravel在渲染视图时已经处理了 route
方法。没有 id
参数,路由生成失败。如何获取带有参数的路由基础?
在 Js 中你可以做这样的事情。
var postId = $(this).data('post-id');
var url = "{{ route('data.post', ':url') }}";
url = url.replace(':url', postId);
对于多个通配符
var postId = $(this).data('post-id');
var anotherId = 1;
var url = "{{ route('test', [':url',':url1']) }}";
url = url.replace(':url', postId);
url = url.replace(':url1', anotherId);
希望对您有所帮助。
这是另一种不太依赖前端代码的方法:
设置路由参数为可选:
Route::get('data/posts/{post?}', 'DataController@post')
->name('data.posts);
现在,您可以轻松调用基本路由并在 JS 中附加 id:
$(".post-links").click(function() {
var postId = $(this).data('post-id');
$.get( "{{ route('data.posts') }}/" + postId, function(data) {
// process the data...
});
});
比替换字符串更整洁!
这确实有一些需要避免的陷阱,即可选参数使 /data/posts
之类的路由成为有效路由,因此您只需要在帖子为 null
的情况下处理该异常。
我认为这是一个更好的解决方案,所以我将其作为正确答案,但我也喜欢其他解决方案。
更新: 考虑到原始问题,即关于占位符或可替换值的问题,另一个答案实际上是正确的。我自己的这个答案是使用占位符的替代方法,所以我会将另一个答案标记为正确答案。
我有一条路线 returns post 数据在 JSON:
Route::get('posts/{post}/data', 'PostController@getData')->name('data.post');
前面JS调用:
<a href="#" data-post-id="{{ $post->id }}" class="post-links">{{ $post->title }}</a>
点击是这样绑定的:
$(".post-links").click(function() {
var postId = $(this).data('post-id');
$.get( "{{ route('data.post') }}" + postId, function(data) {
// process the data...
});
});
这里的问题是 get
的 URL 必须在前端生成,具体取决于点击了哪个 link,但是 Laravel在渲染视图时已经处理了 route
方法。没有 id
参数,路由生成失败。如何获取带有参数的路由基础?
在 Js 中你可以做这样的事情。
var postId = $(this).data('post-id');
var url = "{{ route('data.post', ':url') }}";
url = url.replace(':url', postId);
对于多个通配符
var postId = $(this).data('post-id');
var anotherId = 1;
var url = "{{ route('test', [':url',':url1']) }}";
url = url.replace(':url', postId);
url = url.replace(':url1', anotherId);
希望对您有所帮助。
这是另一种不太依赖前端代码的方法:
设置路由参数为可选:
Route::get('data/posts/{post?}', 'DataController@post')
->name('data.posts);
现在,您可以轻松调用基本路由并在 JS 中附加 id:
$(".post-links").click(function() {
var postId = $(this).data('post-id');
$.get( "{{ route('data.posts') }}/" + postId, function(data) {
// process the data...
});
});
比替换字符串更整洁!
这确实有一些需要避免的陷阱,即可选参数使 /data/posts
之类的路由成为有效路由,因此您只需要在帖子为 null
的情况下处理该异常。
我认为这是一个更好的解决方案,所以我将其作为正确答案,但我也喜欢其他解决方案。
更新: 考虑到原始问题,即关于占位符或可替换值的问题,另一个答案实际上是正确的。我自己的这个答案是使用占位符的替代方法,所以我会将另一个答案标记为正确答案。