【问题标题】:Laravel generate get route with parameters with data from ajaxLaravel 使用来自 ajax 的数据生成带有参数的 get 路由
【发布时间】:2018-03-04 01:00:35
【问题描述】:

我正在发送一个 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');

问题在于我需要为产品链接生成的&lt;a href&gt; 在 laravel 中,当我打印产品时,我会这样称呼它route('product', $product-&gt;id),但在这种情况下,如何将产品 ID 传递给路由函数以生成链接?

【问题讨论】:

  • 显示你的路由代码
  • Route::get('/product/{slug}', 'ProductController@show')-&gt;name('product'); 不是 id 是蛞蝓,但我认为没关系
  • html += '&lt;a href="product-route-here"&gt;'你想在这里使用路由吗?
  • 是的,问题是我不知道如何将产品 slug 作为参数传递
  • AJAX 代码在哪里?在 javascript 文件中还是在视图文件中?

标签: php jquery ajax laravel


【解决方案1】:

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

&lt;script&gt;var product_url = "{{url(' / ')}}/product/";&lt;/script&gt;

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

html += '&lt;a href="' + product_url + product.product_id + '"&gt;'

【讨论】:

    【解决方案2】:

    如果你在product 中有id 则从

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

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

    还可以在末尾使用终止符号冒号;,如果您要制作缩小的js,这将有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 2017-10-21
      • 2017-07-10
      • 1970-01-01
      • 2016-01-28
      • 2018-08-31
      • 2015-04-17
      相关资源
      最近更新 更多