Laravel使用来自ajax的数据生成带有参数的get路由

时间:2017-09-22 12:29:29

标签: php jquery ajax laravel

我正在寻找ajax请求来获取这样的产品:

$.ajax({
    url: '{{ route('filter-products') }}',
    type: 'POST',
    data: {_token: '{{ csrf_token() }}', filters: filters, category_id: {{ $category->id }} }
})
.done(function(products) {
    console.log(products)

    let html = ''
    for(product of products) {
        html += '<div class="col-md-4 women-grids wp1 animated wow slideInUp" data-wow-delay=".5s">' 
            html += '<a href="product-route-here">'

            html += '<div class="product-img">'
                html += 
            html += '</div>'

            html += '</div>'
            console.log(html)
    }
})
.fail(function() {
    console.log("error")
})
.always(function() {
    console.log("complete")
})

我的路线:

Route::get('/product/{slug}', 'ProductController@show')->name('product');

问题在于我需要为产品链接生成<a href> 在laravel中,当我打印产品时,我将其称为route('product', $product->id),但在这种情况下,如何将产品ID传递给路由功能以生成链接?

2 个答案:

答案 0 :(得分:3)

如果您id改变了product

html += '<a href="product-route-here">'

html += '<a href="/product/"'+product.id+'>'

如果你要制作缩小的js,最后也会使用终止符号冒号;

答案 1 :(得分:2)

如果您的ajax代码位于blade文件上,则在该视图文件中添加以下行。这一行将生成url直到产品,然后你可以在你的ajax代码中连接你的id。

<script>var product_url = "{{url(' / ')}}/product/";</script>

在您的ajax代码中添加以上行使用product_url变量后,如下面的代码。

html += '<a href="' + product_url + product.product_id + '">'

相关问题