json - django,如何触发 Ajax 错误函数()
问题描述
该场景是将物品添加到购物车并选择带有它的面料。我想通过弹出警报显示两个错误:
a)当没有选择颜色时/例如一般错误
b) 每个购物车只允许 1 件具有相同面料的物品
发出(a)一般错误消息有效。
但我不确定如何从 django 的视图中的 if 语句触发我的 ajax 的错误警报。
我的 Ajax 表单:
var productForm = $(".form-product-ajax")
productForm.submit(function(event){
event.preventDefault();
var thisForm = $(this)
var actionEndpoint = thisForm.attr("data-endpoint");
var httpMethod = thisForm.attr("method");
var formData = thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function(data){
var submitSpan = thisForm.find(".submit-span")
if (data.added){
$.alert({
title: "Success",
content: "Product added",
theme: "modern",
})
submitSpan.html("<button type='submit' class='btn btn-success'>Add to cart</button>")
}
},
error: function(errorData){
$.alert({
title: "Oops!",
content: data.message,
theme: "modern"
})
}
})
})
Django carts.view 简化
def cart_update(request):
added = False
error_messages = "Please check your selections."
if str(product_obj.type).lower() == "fabric":
cart_obj, new_obj = Cart.objects.new_or_get(request)
fabric_obj = str(Fabric.objects.filter(name__contains=fabric_select).first())
for item in cart_obj.choices.all():
if fabric_obj == item.fabric_note:
error_messages = "You've reached the maximum order amount for this fabric."
# how to trigger ajax error: function() here to give it the new error_message
else:
added = True
cart_obj.choices.add(choices_obj)
if request.is_ajax():
json_data = {
"added": added,
"message": error_messages,
}
return JsonResponse(json_data)
也可以使用 ajax 的 data.message 的 error_message 吗?或者有没有更简单的方法让 ajax 出现两个不同的错误警报?