我遇到了一个我自己无法找到的问题,因此非常感谢您的帮助。
我有一个动态购物车,其中填充了一些 JSON 数据。购物车中的运费也由相同的 json 数据填充。当方法可用时,脚本本身就会起作用。当该国家/地区无法使用某种运输方式时,脚本应显示“不可用”或类似内容。相反,它会返回一个未定义的错误,导致购物车无法工作。经过一番搜索后,我发现当用户来自 A 国(购物车支持)时,Json 字符串中存在变量“methods”。当用户来自国家 B(不支持)时,变量“methods”不会出现在 json 字符串中。显然这会导致错误。 所以我试图实现的是检查变量“methods”是否存在。 我找到了一些答案,例如使用 typeof、HasOwnProperty、lenght() 等,但我不知道如何在下面的脚本中实现它。
我的脚本
<script type="text/javascript">
function getPriceDynamicCart(price){
price = parseFloat(price).toFixed(2);
price = '€ ' + price.replace('.', ',');
return price;
}
function loadDynamicCart(){
var url = "{{ '/cart/' | url }}?format=json";
$.getJSON(url,function(data){
var cartHtml = '';
var priceTotal = 0;
var foundShipment = false;
$.each(data.cart.products, function(index, product){
priceTotal = priceTotal + parseFloat(product.price.price_incl);
productTitleLimit = jQuery.trim(product.fulltitle).substring(0, 19);
cartHtml = cartHtml +
'<div class="cart-product"><div class="cart-quantity">' +product.quantity+' x </div><div class="cart-title"><a href="'+ product.url +'" alt="'+ product.fulltitle + '" title="'+ product.fulltitle + '">' + productTitleLimit + '</a></div><div class="cart-price">' + getPriceDynamicCart(product.price.price_incl) + '</div></div>';
});
$.each(data.cart.shipping.methods, function(index, method){
if(!foundShipment && !method.cod && !method.pickup) {
priceTotal = priceTotal + parseFloat(method.price.price_incl);
cartHtml = cartHtml +
'<div class="cart-shipping"><a class="vracht" style="cursor:pointer;" rel="nofollow">Verzendkosten:<br />(Vervallen bij afhalen)</a><div class="cart-price"> ' + getPriceDynamicCart(method.price.price_incl) + '</div></div>';
foundShipment = true;
}
});
cartHtml = cartHtml +
'<div class="cart-total"><div class="total">Totaal(incl. btw): <span>' + getPriceDynamicCart(priceTotal) + '</span></div>';
$('#dynamic_cart').html(cartHtml);
});
}
$().ready(function(){
loadDynamicCart();
});
</script>
最佳答案
if(data.cart.shipping.methods !== undefined){
$.each(data.cart.shipping.methods, function(index, method){
if(!foundShipment && !method.cod && !method.pickup) {
priceTotal = priceTotal + parseFloat(method.price.price_incl);
cartHtml = cartHtml +
'<div class="cart-shipping"><a class="vracht" style="cursor:pointer;" rel="nofollow">Verzendkosten:<br />(Vervallen bij afhalen)</a><div class="cart-price"> ' + getPriceDynamicCart(method.price.price_incl) + '</div></div>';
foundShipment = true;
}
});
}else{
cartHtml = cartHtml +
'<div class="cart-shipping"><a class="vracht" style="cursor:pointer;" rel="nofollow">Verzendkosten:<br />(Vervallen bij afhalen)</a><div class="cart-price">**Anything you care to write**</div></div>';
}
这应该有效。
编辑,我添加了一个 else 语句来设置 cartHtml 变量,以便您将来使用时拥有更大的灵 active 。
关于jquery - 检查 json 字符串中是否存在变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13256123/