Javascript Can';t获取ajax数据,使用Post方法发送到Django视图
我试图获取/捕获作为Post方法从ajax发送的数据。我相信数据发送正确,因为我可以在控制台中看到发送数据。我想我对这个观点有意见。这是我的密码 home.htmlJavascript Can';t获取ajax数据,使用Post方法发送到Django视图,javascript,django,ajax,Javascript,Django,Ajax,我试图获取/捕获作为Post方法从ajax发送的数据。我相信数据发送正确,因为我可以在控制台中看到发送数据。我想我对这个观点有意见。这是我的密码 home.html <script> document.getElementById('postForm').addEventListener('submit',postName); function postName(e){ e.preventDefault();
<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>
通过XHR请求发送的数据不是表单数据,而是JSON字符串,因此
request.POST
将不包含您希望它包含的键。如果要将数据作为表单数据发送,则应改为使用:
<强>注释< /强>:考虑使用 这是
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);
}
感谢您的回答和关于FetchAPI的建议。我想在这篇评论中添加一个问题,与fetchapi相比,使用ajaxjquery更好吗@阿卜杜勒·阿齐兹Barkat@Rubel看见
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
}
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);
}