[英]Can't get ajax data, send with Post method to Django Views
我試圖獲取/捕獲從 ajax 作為 Post 方法發送的數據。 我相信數據已正確發送,因為我可以在控制台中看到發送數據。 我覺得我的觀點有問題。 這是我的代碼。
主頁.html
<script>
document.getElementById('postForm').addEventListener('submit',postName);
function postName(e){
e.preventDefault();
var name = document.getElementById('id_name').value;
var price = document.getElementById('id_price').value;
var data = {
'name':name,
'price':price,
}
var xhr = new XMLHttpRequest();
xhr.open('POST',"{% url 'ajax-home' %}",true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
var myData= JSON.stringify(data);
xhr.onload = function(){
console.log(myData);
}
xhr.send(myData);
}
</script>
視圖.py
def ajax_home(request):
if request.method == 'POST':
form = ProductForm(request.POST or None)
if 'name' in request.POST:
name = request.POST['name']
else:
name = "stil not found"
p = Product(name=name,price=100)
p.save()
else:
form = ProductForm()
products = Product.objects.all()
context = {
'form':form,
'products': products}
return render(request, 'myapp/home.html', context)
您通過 XHR 請求發送的數據不是表單數據,而是 JSON 字符串,因此request.POST
不會包含您希望它包含的那些鍵。 如果您想將數據作為表單數據發送,您應該使用FormData
[developer.mozilla.org] :
function postName(e){
e.preventDefault();
var name = document.getElementById('id_name').value;
var price = document.getElementById('id_price').value;
var formData = new FormData(); // Create form data here
formData.append('name', name);
formData.append('price', price);
var xhr = new XMLHttpRequest();
xhr.open('POST',"{% url 'ajax-home' %}",true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhr.send(formData); // Send form data
}
注意:考慮使用Fetch API [developer.mozilla.org] ,它是
XMLHttpRequest
的現代替代品。
您正在創建一個 JSON 字符串並嘗試將其發布為application/x-www-form-urlencoded
,下面的數據構造正確
function postName(e){
e.preventDefault();
var name = document.getElementById('id_name').value;
var price = document.getElementById('id_price').value;
var data = 'name='+encodeURIComponent(name)='&price='+encodeURIComponent(price);
var xhr = new XMLHttpRequest();
xhr.open('POST',"{% url 'ajax-home' %}",true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhr.onload = function(){
console.log(data);
}
xhr.send(data);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.