[英]Getting data from controller to the view Laravel with Javascript
I'm trying to get a selected product(id) from view to controller but it only shows the first product(id).我试图从视图中获取选定的产品(id)到 controller,但它只显示第一个产品(id)。 So I have a loop of products which shows image of each product what I want is when a user select any image it should send the id according to the selected product.
所以我有一个产品循环,它显示每个产品的图像我想要的是当用户 select 任何图像它应该根据所选产品发送 id 时。 So far it only pick the first product id even if I click the last product(image) or any different image it only send the first product id.
到目前为止,即使我单击最后一个产品(图像)或任何其他图像,它也只选择第一个产品 ID,它只发送第一个产品 ID。 How can I fix this?
我怎样才能解决这个问题?
Blade刀
@foreach($products as $product)
@if(count($product->ProductsPhoto))
<a href="javascript:;" class="view-product" >
<img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt="" >
</a>
@else
@endif
@endforeach
Javascript Javascript
<?php $id = $product->id; ?>
<script>
$('.view-product').on("click", function(event) {
$("#view-product").modal('show');
$.ajax({
url: '{{route('view.producT', $id)}}',
type: 'GET',
dataType: 'json',
}).done(function(response) {
console.log('received this response: '+response);
});
});
</script>
Route路线
Route::get('view-product/{id}', 'HomeController@viewProduct')->name('view.producT');
Controller Controller
public function viewProduct($id)
{
dd($id);
}
Of course you are not sending the id on each product当然,您不会在每个产品上发送 id
you are sent the id by using <?php $id = $product->id; ?>
使用
<?php $id = $product->id; ?>
<?php $id = $product->id; ?>
and $product
was from @foreach($products as $product) @endoferach
<?php $id = $product->id; ?>
和$product
来自@foreach($products as $product) @endoferach
however $id
would be return the same id但是
$id
将返回相同的 id
you can send the product id
on html and get it from javascript您可以在 html 上发送
product id
并从 javascript 获取
@foreach($products as $product)
@if(count($product->ProductsPhoto))
<a class="view-product" id="{{$product->id}}">
<img src="{{Storage::url($product->ProductsPhoto[0]->filename)}}" alt="" >
</a>
@endif
@endforeach
thats how your a href
by adding id="{{$product->id}}"
通过添加
id="{{$product->id}}"
这就是你a href
<script>
$('.view-product').on("click", function(event) {
var product_id = $(this).attr("id"); //this how you get the product_id
var url = '{{route('view.producT',[":product_id"])}}'; // you cant combine js value on laravel route
//then you need to replace it using below way
url = url.replace(':product_id', product_id);
$("#view-product").modal('show');
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
}).done(function(response) {
console.log('received this response: '+response);
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.