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

标签 python ajax django jquery

我已经获得成功将商品添加到购物车的想法。但是,我只希望它能够 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');

关于python - 添加 "Item"后对 div 进行 Ajaxing 刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9846854/

相关文章:

python - 如何更新 django cached_property

python - 如何组合 WebDriver find_elements_by* 调用,同时跟踪结果的顺序?

python - 无法在 Jupyter 笔记本中读取 avro

javascript - 将 JSON 数据解析为 Chart.js 条形图

javascript : window. location.href/window.open 在 iframe 上不起作用

php - 当设置保存 php 和 ajax 时,密码字段更新为空

django - 访问Django模型字段标签和help_text

Python Gtk Glade 应用程序结构。最佳实践是什么?

Python C API 检查 int64 是否无符号

python - Windows 上的 Celery + Django : debugging asynchronous tasks