【问题标题】:How do you update a django template context variable after an AJAX call?AJAX 调用后如何更新 django 模板上下文变量?
【发布时间】:2016-05-11 23:57:54
【问题描述】:

我有一个表格 Product 显示一组产品的信息。

    <table id="item_table" class="table table-sm table-hover table-bordered">
        <thead class="thead-inverse">
        <tr>
            <th colspan="2">Date</th>
            <th colspan="6">Product name</th>
            <th colspan="2">Category</th>
            <th colspan="2">Amount</th>
        </tr>
        </thead>
        <tbody>
            {% for item in product_list %}
            <tr>
                <td colspan="2">{{ item.date }}</td>
                <td id="item_name_format" colspan="6">{{ item.name }}</td>
                {% if item.category_id %}
                <td id="item_name_format" colspan="2">{{ item.category_id.level1_desc }}</td>
                {% endif %}
                <td id="item_amt_format" colspan="2">${{ item.amount|intcomma }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>

我正在使用下面的 Ajax 调用你更新表。

$(document).ready(function(){

// Submit post on submit
$('.item_num').on('click', function(event){
    event.preventDefault();
    var item_num = $(this).attr('id');
    update_item(item_num);
});

function update_item(item_num) {
    console.log(item_num) // sanity check
    $.ajax({
        type: 'GET',
        url:'update_items', 
        data: { 'item_num': item_num },

        success: function(result){
            console.log(result);
            ???$('item_table').product_list = result;???
        },
... more code

如何使用 Ajax 调用中的“结果”更新变量 product_list?

这应该更新表格吧?

谢谢

【问题讨论】:

  • 您必须序列化您的新产品列表项,将它们传递回您的 ajax 回调,然后迭代表体,通过 JS 为每个新项目创建一个新行。这当然是可能的,但@doniyors 的回答更聪明、更高效。

标签: jquery ajax django django-templates


【解决方案1】:

你不能这样。更好的方法是通过 ajax 加载 html 的那部分。

你的 ajax 视图:

def update_items(request):
    product_list = your_data
    return render(request, 'table_body.html', {'product_list':product_list})

你的主要html:

<tbody class="table_body">
   {% include 'table_body.html' %}
</tbody>

table_body.html:

{% for item in product_list %}
  <tr>
     <td colspan="2">{{ item.date }}</td>
     <td id="item_name_format" colspan="6">{{ item.name }}</td>
     {% if item.category_id %}
      <td id="item_name_format" colspan="2">{{ item.category_id.level1_desc }}</td>
     {% endif %}
      <td id="item_amt_format" colspan="2">${{ item.amount|intcomma }}</td>
  </tr>
{% endfor %}

你的 ajax 应该是这样的:

function update_item(item_num) {
    console.log(item_num) // sanity check
    $('.table_body').html('').load(
        "{% url 'update_items' %}?item_num=" + item_num
    ); // <--- this code instead of $.ajax(lala)

你在这里使用load()

【讨论】:

  • 谢谢。我在我的 AJAX 函数中进行哪些更改以返回 HTML?现在,该 html 显示在开发者的控制台中,但没有在 main.html 中更新。
  • @HC 抱歉,忘记了那部分。更新了问题。我没有测试它,如果它不起作用,请告诉我
  • @HC 不要忘记新的 css 类 table_body :)
  • 谢谢!它主要工作。几个后续问题:1)假设item_table的跨度为12(bootstrap),table_body现在渲染的跨度为8或9。不知道这个方法是否改变了bootstrap的格式?不清楚为什么格式会改变我... 2)在这个实现中,如果用户按下后退按钮,用户将永远无法回到相同的状态。有没有办法使用 Ajax 或其他方式来保存当前状态?
  • 我发现了为什么渲染看起来有点滑稽。由于某种原因,更新后的表在代码中有 /。例如在 colspan 中:Jan. 2016 年 5 月 。你知道这是为什么以及如何解决吗?
【解决方案2】:

您需要首先为您的产品项目创建模型

然后在您的views.py home 函数中,从数据库中加载项目并将其传递给上下文

示例:

myProduct = Products.objects.all()
context = {'myList': myProduct}
return render(request, "home.html", context)

然后将此 java 代码添加到您的模板中,如果用户想要添加项目或将其从卡列表中删除,则调用它

喜欢:

onClick="toggleCardItem({{item.id}})"

然后

function toggleCardItem(itemId){
     $.ajax({
        type: 'POST',
        url: 'client/add/card',
        data: {'id': itemId},
        success: function(res){
             location.reload();
        }
     })
}

蟒蛇模板:

{% for item in myList %} etc.....

现在在你的views.py创建

@csrf_exempt
def add_to_card(request):
   if request.method == "POST":
       item_id = request.POST.get("id")
       key = request.session.session_key
       if key:
           find = Clients.objects.filter(session_key=key)
           if find.exists():
               find = find.get()
               card = find.card_list if find.card_list else "[]"
               card = eval(card)
               item_id = int(item_id)
               if item_id in card:
                   card.remove(item_id)
               else:
                   card.append(item_id)
               find.card_list = card
               find.save()
               return HttpResponse("Success")
           else:
               raise PermissionDenied("This page is private, you not allowed to entered!!!")
       else:
           raise PermissionDenied("This page is private, you not allowed to entered!!!")
   else:
       raise PermissionDenied("This page is private, you not allowed to entered!!!")

导入python库:

from django.views.decorators.csrf import csrf_protect, csrf_exempt

现在在 url.py 中添加

path("client/add/card", views.add_to_card, name="Add to Card"),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-06
    • 2019-02-05
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-01-29
    • 2013-09-18
    相关资源
    最近更新 更多