您需要修改脚本以包含csrfmiddlewaretoken 并使用XmlHttpRequest 发送数据(我假设您没有使用jquery):
<script>
// Standard django function to get csrf_token. More info:
// https://docs.djangoproject.com/en/2.2/ref/csrf/#acquiring-the-token-if-csrf-use-sessions-and-csrf-cookie-httponly-are-false
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const listNode = document.getElementById('list');
let brands = [];
function addLi() {
let txtVal = document.getElementById('txtVal').value,
liNode = document.createElement("LI"),
txtNode = document.createTextNode(txtVal);
liNode.appendChild(txtNode);
listNode.appendChild(liNode);
// Save newly added brand to array
brands.push(txtVal);
}
function ComAction() {
// Prepare AJAX request
let xhr = new XMLHttpRequest(),
data = new FormData();
// Add token
data.append('csrfmiddlewaretoken', getCookie('csrftoken'));
// Add all brands
brands.forEach(function (brand) {
data.append('brand', brand);
});
// We are sending it via POST request to url '/'
xhr.open('POST', '/', true);
xhr.onload = function () {
if (xhr.status === 200) {
alert('Data received successfully. Brands are ' + xhr.responseText);
} else if (xhr.status !== 200) {
alert('Request failed.');
}
};
// Actually send request
xhr.send(data);
}
</script>
您的 django 端点可以像这样处理品牌:
views.py:
def index(request):
if request.method == 'POST':
brands = request.POST.getlist('brand')
return HttpResponse(", ".join(brands))
return render(request, 'index.html')
如果你想让 django 发送数据和重定向用户,修改脚本:
// ...
xhr.open('POST', '/', true);
xhr.onload = function () {
if (xhr.status === 200) {
data = JSON.parse(xhr.responseText);
alert('Data received successfully. Brands are ' + data.brands);
window.location.replace(data.redirect_url);
} else if (xhr.status !== 200) {
alert('Request failed.');
}
};
xhr.send(data);
和 Django:
views.py:
def index(request):
if request.method == 'POST':
brands = request.POST.getlist('brand')
response_data = {
'brands': brands,
'redirect_url': '/new_url'
}
return JsonResponse(response_data)
return render(request, 'index.html')