简体   繁体   English

使用 AJAX 从 Django 模型中获取数据并显示在 html 表中

[英]Get data from Django model and display in a html table using AJAX

I've searched and implemented so many different ways to display a html table, using AJAX, from a JsonResponse (Django) - but to no avail.我已经搜索并实现了许多不同的方式来显示 html 表,使用 AJAX,来自 JsonResponse (Django) - 但无济于事。

Currently, the furthest I've gotten is a response to the network console:目前,我得到的最远的是对网络控制台的响应:

{"products": "[{\"model\": \"products.product\", \"pk\": 2, \"fields\": {\"name\": \"Bag\", \"description\": \"Carries items conspicuously \", \"price\": \"10.99\"}}, {\"model\": \"products.product\", \"pk\": 3, \"fields\": {\"name\": \"iPhone 8 Plus\", \"description\": \"a mobile device from Apple\", \"price\": \"850.00\"}}, {\"model\": \"products.product\", \"pk\": 8, \"fields\": {\"name\": \"Shoes\", \"description\": \"For your feet\", \"price\": \"49.50\"}}, {\"model\": \"products.product\", \"pk\": 9, \"fields\": {\"name\": \"Gloves\", \"description\": \"For your hands\", \"price\": \"2.99\"}}, {\"model\": \"products.product\", \"pk\": 10, \"fields\": {\"name\": \"Blanket\", \"description\": \"Keep warm\", \"price\": \"13.79\"}}, {\"model\": \"products.product\", \"pk\": 11, \"fields\": {\"name\": \"Gown\", \"description\": \"Sleep time\", \"price\": \"25.99\"}}]"}

but I want this dictionary to display on my html table via ajax但我希望这本字典通过 ajax 显示在我的 html 表上

My django model looks like this:我的 Django 模型如下所示:

class Product(models.Model):
    def __str__(self):
        return self.name
    name = models.CharField(max_length = 200)
    description = models.TextField()
    price = models.DecimalField(decimal_places=2,max_digits=100000) 

my django view:我的 Django 视图:

def product_list(request):

    productData = serializers.serialize("json", Product.objects.all())
    return JsonResponse({"products": productData})

my html page body:我的 html 页面正文:

<body style='text-align:center'>
<table class="table table-striped" id="product-table">
    <thead class="thead-dark"><th>Item<th>Description<th>Price</th><th></th></thead>


    <tr>
        <form id="add-product">{% csrf_token %}
            <td><a><input type="text" class="form-control form-control-sm" id="newProductName" placeholder="Product name"></a></td>
            <td><a><input type="text" class="form-control form-control-sm" id="newProductDesc" placeholder="Product description"></a></td>
            <td><a><input type="text" class="form-control form-control-sm" id="newProductPrice" placeholder="£--.--"></a></td>
            <td><button type="submit" class="btn btn-primary btn-sm" id="newProductSubmit">add</button></td>
        </form>
    </tr>

</table>



<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="{% static 'main.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

and my ajax function to get the jsonresponse:和我的 ajax 函数来获取 jsonresponse:

$(document).ready(function() {
    $.ajax({
        url: 'products/getProducts/',
        datatype: 'json',
        type: 'GET',
        success: function (data) {
            alert("Got data!")
            jData = JSON.parse(data)
            alert("got json products!");
        }
    });
});

with the ajax, I am aware I'm missing something to convert the data to html and append to my table, but when I tried this it simply didn't add anything使用 ajax,我知道我缺少将数据转换为 html 并附加到我的表格的内容,但是当我尝试这样做时,它根本没有添加任何内容

I just give you an example of how a table can be created in HTML from the javascript JSON string data what you provided above:我只是给你一个例子,说明如何从你上面提供的 javascript JSON 字符串数据在 HTML 中创建一个表:

<div>
    <table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
    <tr>
        <th width="30%">Name</th>
        <th width="50%">Description</th>
        <th width="12%">price</th>
    </tr>
</thead>
    <tbody id="tableData"></tbody>
</table>
</div>

<style>      
table, td {
    border: 1px solid black;
}
</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script language="javascript" type="text/javascript">

var newProducts = {"products": "[{\"model\": \"products.product\", \"pk\": 2, \"fields\": {\"name\": \"Bag\", \"description\": \"Carries items conspicuously \", \"price\": \"10.99\"}}, {\"model\": \"products.product\", \"pk\": 3, \"fields\": {\"name\": \"iPhone 8 Plus\", \"description\": \"a mobile device from Apple\", \"price\": \"850.00\"}}, {\"model\": \"products.product\", \"pk\": 8, \"fields\": {\"name\": \"Shoes\", \"description\": \"For your feet\", \"price\": \"49.50\"}}, {\"model\": \"products.product\", \"pk\": 9, \"fields\": {\"name\": \"Gloves\", \"description\": \"For your hands\", \"price\": \"2.99\"}}, {\"model\": \"products.product\", \"pk\": 10, \"fields\": {\"name\": \"Blanket\", \"description\": \"Keep warm\", \"price\": \"13.79\"}}, {\"model\": \"products.product\", \"pk\": 11, \"fields\": {\"name\": \"Gown\", \"description\": \"Sleep time\", \"price\": \"25.99\"}}]"};    

var mainObj = JSON.parse(newProducts.products); // I created an object from the json response

// you can iterate over the javascript Object

var k = '<tbody>'

    for(i = 0;i < mainObj.length; i++){             
        k+= '<tr>';
        k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
        k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
        k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
        k+= '</tr>';
    }
    k+='</tbody>';
    document.getElementById('tableData').innerHTML = k;

</script>

And this is a simple table result of the above code:这是上述代码的简单表格结果:

来自 json 数据响应的 HTML 表

I hope this can show you some direction.我希望这可以为您指明方向。 You can of course style the table (or create the table other ways) and you can access all of the other data studying and using this example.您当然可以设置表格样式(或以其他方式创建表格),并且您可以访问所有其他研究和使用此示例的数据。

So, you should just extend your Ajax with calling the added javascript function at success: which I placed in to your jQuery/javasript.因此,您应该通过在成功时调用添加的 javascript 函数来扩展您的 Ajax 我将其放入您的 jQuery/javasript。

$(document).ready(function() {
    $.ajax({
        url: 'products/getProducts/',
        datatype: 'json',
        type: 'GET',
        success: function (data) {
            alert("Got data!")
            jData = JSON.parse(data)
            alert("got json products!");
            tableFromResponse(jData);
        }
    });
});

function tableFromResponse(responseData) {

        var mainObj = JSON.parse(responseData.products);

        var k = '<tbody>'

        for(i = 0;i < mainObj.length; i++){

            k+= '<tr>';
            k+= '<td>' + mainObj[i]["fields"]["name"] + '</td>';
            k+= '<td>' + mainObj[i]["fields"]["description"] + '</td>';
            k+= '<td>' + mainObj[i]["fields"]["price"] + '</td>';
            k+= '</tr>';
        }
        k+='</tbody>';
        document.getElementById('tableData').innerHTML = k;
}

(of course, the lot of json.parse step could be left out from the code if it's causing trouble. Since I wrote the code without real response data from Django in this case). (当然,很多 json.parse 步骤如果引起麻烦,可以从代码中删除。因为在这种情况下,我编写的代码没有来自 Django 的真实响应数据)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用jQuery,Ajax,json在html表中显示数据库中的行 - Display rows from database in html table using jQuery, Ajax, json 从AJAX API获取数据并将其显示在HTML文档中 - Get data from AJAX API and display it in HTML document 无法从ajax请求获取json数据以在html中显示 - Cannot get json data from ajax request to display in html 使用循环在 HTML 中显示来自 jQuery.ajax 的 json 数据 - Display json data from jQuery.ajax in HTML using loop 使用HTML页面或模板中的Django-REST-Framework从Django中创建的API的前端获取/显示API数据 - Get/Display API data at front end from an API created in Django using Django-REST-Framework in an HTML page or Template 将 ajax 的 JSON 响应显示为 HTML 或表格 - Display JSON response from ajax as HTML or table 如何使用 js table 将数据从 json 显示为 HTML - How to display data from json into HTML using js table 使用jquery从json获取特定数据并以html显示 - Using jquery to get specific data from json and display in html 使用AJAX在模板的表格中显示Django视图返回的字典数据 - Use AJAX to display dictionary data returned by Django view in a table on the template 从php的表的所有行接收JSON编码数据,并使用ajax在html表中显示 - Receive JSON ENCODED Data from all rows of table from php and show in html table using ajax
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM