我有这个Jquery / Ajax代码,它发送GET
请求,我认为有很多重复项。如何减少此代码?
$(".add_to_cart").click(function() {
product_slug = $(this).attr("data-slug")
data = {
product_slug: product_slug,
},
$.ajax({
type: "GET",
url: "{% url 'cart:cart_create' %}",
data: data,
success: function(data) {
$(".cart_score").html(data.cart_length + " товаров " + data.cart_total + " ₽")
},
});
});
$(".update_cart").click(function() {
product_slug = $(this).attr("data-slug")
quantity = $(this).val()
data = {
product_slug: product_slug,
quantity: quantity,
}
$.ajax({
type: "GET",
url: "{% url 'cart:cart_update' %}",
data: data,
success: function(data) {
$(".cart_score").html(data.cart_length + " товаров " + data.cart_total + " ₽")
$(".cart_total").html(data.cart_total + " ₽")
$(".item_total_price-"+product_slug).html(data.cart_price + " ₽")
},
});
});
$(".del_from_cart").click(function() {
product_slug = $(this).attr("data-slug")
data = {
product_slug: product_slug,
},
$.ajax({
type: "GET",
url: "{% url 'cart:cart_delete' %}",
data: data,
success: function(data) {
$(".cart_score").html(data.cart_length + " товаров " + data.cart_total + " ₽")
$(".cart_total").html(data.cart_total + " ₽")
$(".item_product-"+product_slug).css("display", "none")
if (data.cart_length < 1) {
$(".cart_score").html("<a href='{% url 'cart:cart_show' %}' class='cart_score'>Корзина пустая</a>")
$(".cart_block").html("<p>Корзина пуста <a href='{% url 'shop:product_list' %}'>выбрать модель</a></p>")
}
},
});
});
$(".clear_cart").click(function() {
$.ajax({
type: "GET",
url: "{% url 'cart:cart_clear' %}",
success: function() {
$(".cart_score").html("<a href='{% url 'cart:cart_show' %}' class='cart_score'>Корзина пустая</a>")
$(".cart_block").html("<p>Корзина пуста <a href='{% url 'shop:product_list' %}'>выбрать модель</a></p>")
},
});
});
我是Java的新手,有什么想法吗?至少是一个小例子:)
答案 0 :(得分:2)
以这种方式创建一个通用的Ajax
function CommonAjaxCall(type, url, parameters, successCallback) {
$.ajax({
type: type,
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log('error');
}
});
}
CommonAjaxCall(type, url, pars, onSuccess);
function onSuccess(result) {
//perform your logic from here
}