Skip to main content
 首页 » 编程设计

python之添加 "Item"后对 div 进行 Ajaxing 刷新

2025年05月04日29unruledboy

我已经获得成功将商品添加到购物车的想法。但是,我只希望它能够 ajax 刷新(某种程度上)'#cart' div,同时仍在原始页面上。换句话说,该项目已添加到购物车中,但仅在我手动刷新时才会显示。我只希望它看起来流畅且符合 ajax 风格。

View .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 初学者。我的脚本显然有问题。我只是不知道从这里去哪里。

提前感谢您的帮助。

请您参考如下方法:

我在你的代码中看不出你的意思。但这应该重新加载#cart 元素..尽管可能有更好的方法来做到这一点而无需再次下载整个页面只是为了一个元素上的内容

$('#cart').load('ajax/test.html #cart');