【发布时间】:2012-03-23 21:43:23
【问题描述】:
我已获得成功将我的商品添加到购物车的视图。但是,我只希望它在仍然在原始页面上的同时刷新(各种)'#cart' div。换句话说,该商品已添加到购物车中,但仅在我手动刷新时才显示。我只是希望它看起来平滑和 ajax-y。
Views.py:
@login_required
def add(request, profile):
if request.method != 'POST':
return HttpResponseNotAllowed('POST')
try:
item = Item.objects.get(slug=slugify(request.POST['itemname']))
except ObjectDoesNotExist:
item = Item(name=request.POST['itemname'])
item.save()
profile = Profile.objects.get(user=request.user)
profile.items.add(item)
response = simplejson.dumps(
{"status": "Successfully added."}
)
return HttpResponse (response, mimetype='application/json')
模板:
<form id="addItemForm" class="form-style" method="POST" action="/item/add/{{ profile }}/">
{% csrf_token %}
<input id="item-input" class="input-text inline required" name="itemname" type="text" />
<button class="blue" type="submit" id="additem">
Add Item
</button>
</form>
脚本:
$('#addItemForm').submit(function(e){
e.preventDefault();
var form = $("#additem").attr("action");
var post_data = $.post($(this).attr('action'), $(this).serialize(), function(data, textStatus, jqXHR){
$('.item-selection').html(data);
result = $.ajax({
url: form,
data: post_data,
type: "POST",
success: function(data) {
//alert("Successfully added");
console.log()
$("#item-selection").replaceWith($('#item-selection', $(html)));
//{[( THIS IS WHERE I'D LIKE IT TO REFRESH)]}
},
error: function(data) {
// return the user to the add item form
$('#addItemForm').html(data);
}
});
});
控制台错误:
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
(我为格式道歉) 我是一个ajax初学者。我的脚本显然有问题。我只是不知道从这里去哪里。
提前感谢您的帮助。
【问题讨论】: