Django 使用来自 Ajax 的成功数据更新模板 div

Posted

技术标签:

【中文标题】Django 使用来自 Ajax 的成功数据更新模板 div【英文标题】:Django update template div with success data from Ajax 【发布时间】:2021-07-14 16:01:57 【问题描述】:

我有选择选项和选择选项我运行 ajax 从我的模型中获取过滤后的数据。以下是我的看法:

我的带有脚本和控制台日志的模板也在下面更新:

我需要帮助如何使用success(books) ajax 获取的新列表更新模板中的列表。 ( $('#stock_list').html([books]) 没有更新列表)

查看.py

​​>
def get_stock_list(request):
if request.method == "GET":
    book_type = request.GET.get('book_type')
    books = list(TextBook.objects.filter(type=book_type).values())
    return JsonResponse("books": books)

stock_report.html:

 % extends 'wstore_base_generic.html' %

 % block content %
 <div class="row">
  <div class="col-lg-12 mt-4">
    <div class="card shadow"  id="stock_report">
        <div class="card-header text-center">                
            <h3 class="display-5">
                Stock Report
            </h3>
             <div class="text-right">


            <h5>
                <select id="book_type" name="book_type" >
                <option  value="" selected="selected">---SELECT---</option>
                   % regroup books by type as type_list %
                      % for type in type_list %
                            <option value=" type.grouper "> type.grouper </option>
                        % endfor %
                 </select> </h5>
             </div>
        </div>
        <div class="card-body" id="stock_list">
            <table id="customers" >
                <thead>
                    <tr>
                        <th>Item Code</th>
                        <th>Item Description</th>
                        <th>Open Qty</th>
                        <th>Received qty</th>
                        <th>Return Qty</th>
                        <th>Issue Qty</th>
                        <th>Adj Qty</th>
                        <th>Balance Qty</th>
                    </tr>                        
                </thead>
                <tbody>

                    % if books %

                    % for book in books %
                    <tr>

                        <td> <a href="% url 'select_stock_report' book.id %"> book.code </a></td>
                        <td>book.name</td>
                        <td>book.open_qty</td>
                        <td>book.recived_qty</td>
                        <td>book.return_qty</td>
                        <td>book.issue_qty</td>
                        <td>book.adj_qty</td>
                        <td>book.bal_qty</td>
                    </tr>
                    % endfor %
                    % else %
                        <tr class="text-center">
                            <td colspan="4">No Transaction have been made yet</td>
                        </tr>
                    % endif %
                </tbody>
            </table>                
        </div>            
    </div>
    <div class="card">
        <div class="card-footer">
            <button class="btn btn-success" id="print_stock" 
onclick="printDiv('stock_report')">Print</button>
        </div>
    </div>
</div>
</div>
%  endblock %
% block js %
<script>

 $(document).on('change', '#book_type', function()
   var that = $(this)
 $.ajax(
    
        type: "GET",
        url: "/get_stock_list",
        dataType: "json",
        data: 
            'book_type': $(this).val(),
            'csrfmiddlewaretoken': 'csrf_token'
        ,
        success: function (books) 
            console.log(books);
            $('#stock_list').html([books]);



        
    ))
 </script>
 % endblock %

我得到了 console.log(books)

 books: array(4)

 
     "books": [
    
        "id": 1,
        "code": "LKG001",
        "type": "BOOK",
        "name": "LKG BOOK 1",
        "open_qty": "0",
        "recived_qty": "328",
        "return_qty": "0",
        "issue_qty": "111",
        "adj_qty": "4",
        "bal_qty": "213",
        "avgcost": "100.55",
        "price": "100.00"
    ,
    
        "id": 2,
        "code": "UKG001",
        "type": "BOOK",
        "name": "UKG BOOK 1",
        "open_qty": "0",
        "recived_qty": "17",
        "return_qty": "0",
        "issue_qty": "9",
        "adj_qty": "0",
        "bal_qty": "8",
        "avgcost": "200.00",
        "price": "200.00"
    ,
    
        "id": 3,
        "code": "UKG002",
        "type": "BOOK",
        "name": "UKG002 BOOKS",
        "open_qty": "0",
        "recived_qty": "0",
        "return_qty": "0",
        "issue_qty": "0",
        "adj_qty": "1",
        "bal_qty": "-1",
        "avgcost": "0.00",
        "price": "200.00"
    ,
    
        "id": 4,
        "code": "001",
        "type": "BOOK",
        "name": "001 TEST",
        "open_qty": "0",
        "recived_qty": "0",
        "return_qty": "0",
        "issue_qty": "0",
        "adj_qty": "0",
        "bal_qty": "0",
        "avgcost": "0.00",
        "price": "0.00"
    
 ]
 

【问题讨论】:

也许不是返回 JSON 响应,而是返回 HTML 响应,以便您可以轻松地将 DOM 中的相关部分替换为从 AJAX 调用中接收到的 HTML。 【参考方案1】:

由于您的数据返回是 json,您可以使用 $.each 循环遍历您的 json 数组,然后使用 value.keyname 从 json 获取值并将这些值附加到 tds 中,最后添加在表 tbody 中生成的这个 html。

演示代码

//suppose this is return from ajax
var books = 
  "books": [
      "id": 1,
      "code": "LKG001",
      "type": "BOOK",
      "name": "LKG BOOK 1",
      "open_qty": "0",
      "recived_qty": "328",
      "return_qty": "0",
      "issue_qty": "111",
      "adj_qty": "4",
      "bal_qty": "213",
      "avgcost": "100.55",
      "price": "100.00"
    ,
    
      "id": 2,
      "code": "UKG001",
      "type": "BOOK",
      "name": "UKG BOOK 1",
      "open_qty": "0",
      "recived_qty": "17",
      "return_qty": "0",
      "issue_qty": "9",
      "adj_qty": "0",
      "bal_qty": "8",
      "avgcost": "200.00",
      "price": "200.00"
    ,
    
      "id": 3,
      "code": "UKG002",
      "type": "BOOK",
      "name": "UKG002 BOOKS",
      "open_qty": "0",
      "recived_qty": "0",
      "return_qty": "0",
      "issue_qty": "0",
      "adj_qty": "1",
      "bal_qty": "-1",
      "avgcost": "0.00",
      "price": "200.00"
    ,
    
      "id": 4,
      "code": "001",
      "type": "BOOK",
      "name": "001 TEST",
      "open_qty": "0",
      "recived_qty": "0",
      "return_qty": "0",
      "issue_qty": "0",
      "adj_qty": "0",
      "bal_qty": "0",
      "avgcost": "0.00",
      "price": "0.00"
    
  ]



/*$(document).on('change', '#book_type', function()
   var that = $(this)
 $.ajax(
    
        type: "GET",
        url: "/get_stock_list",
        dataType: "json",
        data: 
            'book_type': $(this).val(),
            'csrfmiddlewaretoken': 'csrf_token'
        ,
        success: function (books) 
            console.log(books);*/
var html = "";
//loop through json array return
$.each(books.books, function(key, value) 
  //append tr
  html += `<tr> <td> <a href="% url 'select_stock_report' $value.id %">$ value.code </a></td><td>$value.name</td><td>$value.open_qty</td><td>$value.recived_qty</td><td>$value.return_qty</td><td>$value.issue_qty</td><td>$value.adj_qty</td><td>$value.bal_qty</td></tr>`
)

$('#stock_list tbody').html(html); //add datas inside tbody
/* 
    ))*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body" id="stock_list">
  <table id="customers">
    <thead>
      <tr>
        <th>Item Code</th>
        <th>Item Description</th>
        <th>Open Qty</th>
        <th>Received qty</th>
        <th>Return Qty</th>
        <th>Issue Qty</th>
        <th>Adj Qty</th>
        <th>Balance Qty</th>
      </tr>
    </thead>
    <tbody>
      <!--data will come here -->

    </tbody>
  </table>
</div>

【讨论】:

我做了这样的改变,它正在工作: $.each(books, function(index, item) $.each(item, function(index1, item1) html += " "+item1.id+" " ); ) $('#stock_list tbody ').html(html)

以上是关于Django 使用来自 Ajax 的成功数据更新模板 div的主要内容,如果未能解决你的问题,请参考以下文章

上传文件后,如何在 Django 中使用 AJAX 更新表(与 JavaScript 链接)?

带有 jquery 的 Django 模板:现有页面上的 Ajax 更新

使用 Django 和 AJAX 更新数据

在 Django 中使用 AJAX 更新数据库

parseJSON在django模板的ajax成功回调函数中返回null

如何使用 AJAX 和 Django 从 SQL 数据库更新网站上的字段数据