如果有人知道如何做到这一点以及为什么我会收到错误,我会很高兴,我想在forelse里面的route()方法中传递“var size”它是否有些可行?
不管怎样吗?基于单选框(如果大小M和L可用,则会有2个radiobox),如果用户点击添加到卡,它会获得单选框的值,例如(6)= L他们将它传递给ajax路径< / p>
错误:
使用未定义的常量大小 - 假设'size'(查看:C:\ xampp \ htdocs \ EcSc \ resources \ views \ shop \ home.blade.php)
JS:
<script>
var CartCount = {{ Session::has("cart") ? Session::get("cart")->totalQty : "0" }} ;
var size;
@forelse($products as $productsjs)
$("#product-{{$productsjs->id}}").click(function () {
var radios{{$productsjs->id}} = document.getElementsByName('radio-{{$productsjs->id}}');
for (var i = 0, length = radios{{$productsjs->id}}.length; i < length; i++) {
if (radios{{$productsjs->id}}[i].checked) {
// do whatever you want with the checked radio
size = radios{{$productsjs->id}}[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
$.ajax({
type: "get",
url: "{{route("product.addToCartAjax", $productsjs->id, size)}}", // insert product with specific size into session
success: function () {
CartCount++;
$("#shoppingCartCounter").html(CartCount);
console.log("Produkt bol pridani");
console.log("Velkost produktu je : " + size); // size contain value of checked radio box
}
})
});
@empty
@endforelse
</script>
答案 0 :(得分:2)
您无法在PHP中打印javascript变量。将{{ }}
视为<?php ?>
。如果您只是将其插入其中,它可能看起来像<?php echo size; ?>
,这将无效,因为显然大小在这里看起来像一个常数,当然这是未定义的(您的错误)。
相反,你需要在php中声明变量。但是,由于您在运行后执行此操作,因此在呈现页面后,您无法分配PHP变量。那你有什么选择呢?
url: '/products/' + {{$productsjs->id}} + '/add-to-cart-ajax/' + size
laroute.route('product.{id}.addToCartAjax.{size}', {id: '{{$productsjs->id}}', size: size});