微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

jquery – 如何在AJAX调用后更新django模板上下文变量?

我有一个表产品,显示一组产品的信息.
<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调用中的’result’更新变量product_list?

这应该更新表吗?

谢谢

解决方法

你不能这样.更好的方法是通过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()

原文地址:https://www.jb51.cc/jquery/178672.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐