如何从 JavaScript ajax 调用和打印 Django 模板中的视图中的 return 数据发送本地存储数据
How can I send localstorage data from JavaScript ajax call and print return data from views in Django template
我已经在 localStorage 上存储了一些数据(Itemnames 和 ItemIds),现在我想将 itemid 从 ajax 发送到 django 视图。我有 django 的基础知识和学习 Javascript。我试图自己弄清楚,但已经超过 4 天了,我无法成功,任何帮助将不胜感激。
我的Javascript:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: './compare',
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
success: function (data) {
console.log(data)
},
error: function () {
alert("Some problem on passing data");
}
});
});
我的观点:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
"""compare_id=request.POST.getlist('itemIds[]') """
"""compare_id = request.POST.get('compare_id')"""
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
""" return render (request, './ecommerce/compare.html', context)"""
return render (request, './compare.html', context)
else:
context = None
return render(request,'./compare.html', context)
我怎样才能得到有id经过ajax的产品?是否有任何不同的方法可以将这些产品传递给模板,或者我可以像常规的 Django 上下文过程一样做到这一点?
在您的 ajax 中,您应该像这样对数据部分进行字符串化:
$.ajax({
// rest of the code
data: JSON.stringify({'compare_id': compareObj}),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
// access your response as data.product
},
// rest of the code
});
然后在你看来:
import json
from django.http import JsonResponse
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = json.loads(request.POST.get('compare_id'))
ids = compare_id.get('compare_id')
# ids will be list of ids and you can get first id with index
product = get_object_or_404(Products, id=ids[0])
# rest of code
return JsonResponse({'product': product})
从您的 ajax 请求中传递 json 字符串。
$.ajax({
url: './compare',
type: "POST",
data: JSON.stringify({'compare_id': compare }),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
contentType : "application/json",
success: function (data) {
$.each(data, function (key, value) {
if (key == "products") {
for (var i = 0; i < data[key].length; i++) {
var wishlistUrl = "{% url 'ecommerce:add_to_wishlist' %}";
var div = '<div class="compare-col compare-product">';
div += '<a href="#" class="btn remove-product"><i class="w-icon-times-solid"></i></a>';
div += '<div class="product text-center"><figure class="product-media">';
div += '<a href="product.html"><img src="' + data[key][i].product_feature_image.image.url + '" alt="Product" width="228" height="257" />';
div += '</a><div class="product-action-vertical"><a href="#" class="btn-product-icon btn-cart w-icon-cart"></a>';
div += '<a href="#" class="btn-product-icon btn-wishlist w-icon-heart" title="Wishlist" attr_id="' + data[key][i].id + '" ';
div += ' action_url="' + wishlistUrl + '">';
div += '</a></div></figure><div class="product-details"><h3 class="product-name"><a href="product.html">' + data[key][i].name + '</a></h3>';
div += '</div></div></div>';
$('#parentDivElementId').append(div); #--- your parent div element id
}
}
})
},
error: function () {
alert("Some problem on passing data");
}
});
在你的views.py
先获取POST数据
import json
from django.shortcuts import get_list_or_404, render
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
data = json.loads(request.body)
compare_ids = data['compare_id']["itemIds"] if 'itemIds' in data['compare_id'] else []
# since here multiple ids may come you need to use `filter` instead you will get
get() returned more than one Products -- it returned 2!
products = Products.objects.filter(id__in=compare_ids).values()
return JsonResponse({'products ': list(products) }, safe=False) #---- since Queryset is not JSON serializable
else:
context = None
return render(request,'./compare.html', context)
在您的控制台中,您可以看到您的 products
数据。
我已经在 localStorage 上存储了一些数据(Itemnames 和 ItemIds),现在我想将 itemid 从 ajax 发送到 django 视图。我有 django 的基础知识和学习 Javascript。我试图自己弄清楚,但已经超过 4 天了,我无法成功,任何帮助将不胜感激。
我的Javascript:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: './compare',
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
success: function (data) {
console.log(data)
},
error: function () {
alert("Some problem on passing data");
}
});
});
我的观点:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
"""compare_id=request.POST.getlist('itemIds[]') """
"""compare_id = request.POST.get('compare_id')"""
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
""" return render (request, './ecommerce/compare.html', context)"""
return render (request, './compare.html', context)
else:
context = None
return render(request,'./compare.html', context)
我怎样才能得到有id经过ajax的产品?是否有任何不同的方法可以将这些产品传递给模板,或者我可以像常规的 Django 上下文过程一样做到这一点?
在您的 ajax 中,您应该像这样对数据部分进行字符串化:
$.ajax({
// rest of the code
data: JSON.stringify({'compare_id': compareObj}),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
// access your response as data.product
},
// rest of the code
});
然后在你看来:
import json
from django.http import JsonResponse
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = json.loads(request.POST.get('compare_id'))
ids = compare_id.get('compare_id')
# ids will be list of ids and you can get first id with index
product = get_object_or_404(Products, id=ids[0])
# rest of code
return JsonResponse({'product': product})
从您的 ajax 请求中传递 json 字符串。
$.ajax({
url: './compare',
type: "POST",
data: JSON.stringify({'compare_id': compare }),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
contentType : "application/json",
success: function (data) {
$.each(data, function (key, value) {
if (key == "products") {
for (var i = 0; i < data[key].length; i++) {
var wishlistUrl = "{% url 'ecommerce:add_to_wishlist' %}";
var div = '<div class="compare-col compare-product">';
div += '<a href="#" class="btn remove-product"><i class="w-icon-times-solid"></i></a>';
div += '<div class="product text-center"><figure class="product-media">';
div += '<a href="product.html"><img src="' + data[key][i].product_feature_image.image.url + '" alt="Product" width="228" height="257" />';
div += '</a><div class="product-action-vertical"><a href="#" class="btn-product-icon btn-cart w-icon-cart"></a>';
div += '<a href="#" class="btn-product-icon btn-wishlist w-icon-heart" title="Wishlist" attr_id="' + data[key][i].id + '" ';
div += ' action_url="' + wishlistUrl + '">';
div += '</a></div></figure><div class="product-details"><h3 class="product-name"><a href="product.html">' + data[key][i].name + '</a></h3>';
div += '</div></div></div>';
$('#parentDivElementId').append(div); #--- your parent div element id
}
}
})
},
error: function () {
alert("Some problem on passing data");
}
});
在你的views.py
先获取POST数据
import json
from django.shortcuts import get_list_or_404, render
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
data = json.loads(request.body)
compare_ids = data['compare_id']["itemIds"] if 'itemIds' in data['compare_id'] else []
# since here multiple ids may come you need to use `filter` instead you will get
get() returned more than one Products -- it returned 2!
products = Products.objects.filter(id__in=compare_ids).values()
return JsonResponse({'products ': list(products) }, safe=False) #---- since Queryset is not JSON serializable
else:
context = None
return render(request,'./compare.html', context)
在您的控制台中,您可以看到您的 products
数据。