繁体   English   中英

如何使用 vanilla JavaScript 发送表单数据?

[英]How to send post form data using vanilla JavaScript?

我正在尝试使用 vanilla JS 异步从帖子表单中获取数据(避免刷新页面)。 我在某些时候失败了,因为我无法访问表单的数据。

模板.html

 <form method="POST"  autocomplete="off" action="/index" id="mail_form_id">
    {% csrf_token %}
    <input type="email" name="mail_input" id="mail_input">
    <button type="submit" onclick="send_mailform()" ></button>
...

视图.py

...
    if request.is_ajax:
         print(request.POST['mail_input']) #This is not working

脚本.js

// I'm avoiding to refresh using this function
var form = document.getElementById("mail_form_id");
function handleForm(event) { event.preventDefault(); } 
form.addEventListener('submit', handleForm);

function send_mailform(){
    var http = new XMLHttpRequest();
    http.open("POST", "/index", true);
    http.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
    var mail_input = document.getElementById('mail_input').value; 
    http.send(mail_input);
}
...

我一直在搜索,django 1.X 或使用 Jquery 有几种解决方案。 我没有将 getCookie 函数放在 scripts.js 中,但它工作正常。 我试图避免使用 Jquery。 先感谢您!

我认为这不是最好的方法,但可以使用以下方法发送数据:

视图.py

raw_data = request.body #Binary 
data = raw_data.decode("utf-8")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM