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

亚什莫拉尔

我已经从JsonResponse(Django)中搜索并实现了许多使用AJAX显示html表的不同方法,但无济于事。

当前,我得到的最远的是对网络控制台的响应:

{"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\"}}]"}

但是我希望这个字典通过ajax显示在我的html表上

我的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) 

我的django视图:

def product_list(request):

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

我的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>

和我的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!");
        }
    });
});

使用ajax,我知道我缺少将数据转换为html并追加到表中的内容,但是当我尝试这样做时,它根本没有添加任何内容

佐利

我仅向您提供一个示例,说明如何使用上面提供的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>

这是上面代码的简单表结果:

来自JSON数据响应的HTML表

我希望这可以告诉您一些方向。您当然可以设置表的样式(或以其他方式创建表),并且可以访问研究和使用此示例的所有其他数据。

因此,您应该通过成功调用添加的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;
}

(当然,如果造成麻烦,可以从代码中忽略很多json.parse步骤。因为在这种情况下,我编写的代码中没有来自Django的真实响应数据)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用 HTML 表中的 for 循环显示数据库中的 Django 模型

从xml文件中获取数据并使用Ajax和xpath在html表中显示

使用 Ajax 从 Django 模型中获取模态数据

获取与用户名关联的模型数据并将其显示在 Django 中的 HTML 中

使用ajax在表中显示数组数据

更新模型并在 html 表中显示更新的数据

使用ajax和dataType:“ json”从数据库中获取数据以html形式显示

如何使用Flask从Postgresql数据库中获取数据并显示HTML表

为什么我的 django 模型数据不会显示在 html 中

如何从Django模型和HTML模板中获取数据

使用BeautifulSoup从html表中获取数据

Django:从表中获取数据并使用ListView一起显示

使用查询从特定表中获取数据并在Django的管理端显示

如何使用模板获取整个表数据并在django的用户界面中显示它们

使用jquery ajax发布和获取数据,仅在mvc中更新html表行

如何使用 $.ajax() jquery 获取数据并显示到 HTML 网页

在 Django 中使用 OneToOneField 从模型中获取数据

如何使用基于函数的视图在django rest框架中显示html表而不是原始数据?

在Django中显示模型中的正确数据

在Django表中显示数据

如何使用reactjs在表中显示从api获取的数据

如何使用laravel模型中的hasOne关系从2个表中获取数据中的数据

无法使用 jQuery Ajax Bootstrap 模型从数据库中获取更新数据的值 - json 数据

如何从模型函数中获取数据以显示在 Django Admin 中?

使用 AJAX 删除模型数据 - Django

如何使用 AJAX 在 Django 中显示更改的数据

在Django中以模型表单集获取数据

从 Django python 中的 2 模型获取数据

Django - 从模型中获取特定数据