Python 使用JSON数据更新Div时出现问题
继上一个问题之后,我有一个django web应用程序,我试图使用它在HTML页面上显示数据,其中包含使用JsonResponse方法的数据库中的数据。该网站允许用户输入新产品的详细信息。我试图设计它,以便当他们输入详细信息时,下面的Div将自动更新并显示已输入的新项目以及数据库中的现有项目。这是我的密码: 索引页:Python 使用JSON数据更新Div时出现问题,python,jquery,django,get,request,Python,Jquery,Django,Get,Request,继上一个问题之后,我有一个django web应用程序,我试图使用它在HTML页面上显示数据,其中包含使用JsonResponse方法的数据库中的数据。该网站允许用户输入新产品的详细信息。我试图设计它,以便当他们输入详细信息时,下面的Div将自动更新并显示已输入的新项目以及数据库中的现有项目。这是我的密码: 索引页: <!DOCTYPE html> <html> <body> <div> <h2 id="title">Creat
<!DOCTYPE html>
<html>
<body>
<div>
<h2 id="title">Create product</h2>
<input id="name">Name</input>
<br>
<input id="description">Description</input>
<br>
<input id="price">Price</input>
<br>
<button id="add-product">ADD PRODUCT</button>
</div>
<div id="productList">
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('add-product').onclick = function(){
sendData();
getData();
}
function sendData(){
var order = {
name: document.getElementById('name').value,
description: document.getElementById('description').value,
price: document.getElementById('price').value
};
$.ajax({
type: "POST",
url: 'create/product',
data: order,
success: function(newProduct){
console.log("success"),
$('#name').val(""),
$('#description').val(""),
$('#price').val("")
}
});
};
function getData(){
$.ajax({
url: 'view/product',
dataType: 'json',
type: 'GET',
success: function(data){
$.each(data.prod, function(index, element){
$('body').append($('#productList', {
text: element.name
}));
});
}
});
}
</script>
</html>
现在我认为getData()方法的工作原理与在函数的成功部分包含console.log消息时一样,它工作并打印到控制台。然而,它并没有像我希望的那样将产品的细节添加到Div中。提前感谢您对此的解答。这是您的解决方案 函数getData(){ $.ajax({ url:“视图/产品”, 数据类型:“json”, 键入:“GET”, 成功:功能(数据){ $('#productList').empty(); $.each(data.prod,函数(索引,元素){ $('#productList').append(element.name); }); } });
}谢谢你的帮助,不过还是没用。当我添加一条console.log消息时,它返回一条console.log消息,但数据本身没有呈现。
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from products.models import Product
from django.http import HttpResponse, JsonResponse
def index(request):
return render(request, 'index.html')
@csrf_exempt
def createProduct(request):
if request.method == 'POST':
name = request.POST.get('name')
description = request.POST.get('description')
price = request.POST.get('price')
newProduct = Product(
name = name,
description = description,
price = price
)
newProduct.save()
return HttpResponse('')
def viewProduct(request):
if request.method == 'GET':
product_list = Product.objects.all()
products=[]
for prod in product_list:
products.append({"name": prod.name, "description": prod.description, "price": prod.price})
return JsonResponse(products, safe=False)