问题
I'm building an online store using Shopify and have come across some jQuery/Ajax code in the default template that I would like to modify for my needs.
function addToCartSuccess (jqXHR, textStatus, errorThrown){
$.ajax({
type: 'GET',
url: '/cart.js',
async: false,
cache: false,
dataType: 'json',
success: updateCartDesc
});
window.location = "/cart";
$('.add-cart-msg').hide().addClass('success').html('Item added to cart! <a href="/cart" title="view cart">View cart and check out »</a>').fadeIn('300');
}
I added the window.location line myself thinking it would post the message on the Cart page but to no avail. If I remove that code the success message is posted on the product page when the Add to Cart button is pressed so it does actual work without modification.
I also tried creating my own function with a POST command but really I am best guessing as I don't have any previous experience with this level of jQuery/Ajax
function updateCartDesc (jqXHR, textStatus, errorThrown){
$.ajax({
type: 'POST',
url: '/cart',
async: false,
cache: false,
dataType: 'html',
success: function (){('.add-cart-msg').hide().addClass('success').html('Item added to cart! <a href="/cart" title="view cart">View cart and check out »</a>').fadeIn('300');
}
});
Any pointers on where I am going wrong? Tutorials, guides etc. would be wonderful. Thanks
回答1:
You are going to have to redirect the user to the cart page with a param in the URL that tells the cart page to show a message. Something like the below:
Your Ajax add to cart call and callback
$.ajax({
type: 'GET',
url: '/cart.js',
async: false,
cache: false,
dataType: 'json',
success: updateCartDesc
});
var updateCartDesc = function() {
//redirect the user to the cart and pass showSuccess=true in the URL
window.location = "/cart?showSuccess=true";
};
Script on your cart page
$(function() {
//if the current URL contains showSuccess,
//display the success message to the user
if(window.location.href.indexOf('showSuccess') != -1) {
$('.add-cart-msg').hide()
.addClass('success')
.html('Item added to cart!')
.fadeIn('300');
}
});
Just to note that this code assumes you have an element on the /cart page with class add-cart-msg
.
来源:https://stackoverflow.com/questions/11994239/shopify-post-ajax-add-to-cart-success-message-on-cart-page