【发布时间】:2022-01-04 11:30:59
【问题描述】:
我正在尝试使用引导模式实现一个简单的表单,但是每当我提交表单时,我得到的响应都是整个 HTML 页面。请求是 POST。我已经尝试了 StackOverflow 上的几乎所有答案,但没有一个对我有用。
我的模态表单代码:
<div id="alert-box"></div>
<form id="ajax-form" autocomplete="off">
{% csrf_token %}
{{contact_form|crispy}}
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
这是我的 Ajax 代码:
<script type="text/javascript">
const alertBox = document.getElementById('alert-box');
const msgForm = document.getElementById('ajax-form');
const name = document.getElementById('id_name');
const number = document.getElementById('id_phone_number');
const message = document.getElementById('id_message');
const csrf = document.getElementsByName('csrfmiddlewaretoken');
const handleAlerts = (type,text) => {
alertBox.innerHTML = `<div class="alert alert-${type}" role="alert">
${text}
</div>`
}
const url = "";
console.log(csrf);
msgForm.addEventListener('submit',e => {
e.preventDefault();
const fd = new FormData();
fd.append('csrfmiddlewaretoken',csrf[0].value);
fd.append('name',name.value);
fd.append('number',number.value);
fd.append('message',message.value);
$.ajax({
type: 'POST',
url: url,
data: fd,
cache: false,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
success: function(response) {
const sText = `${response.name}`;
handleAlerts('success', sText)
setTimeout(()=>{
alertBox.innerHTML = "";
name.value = "";
number.value = "";
message.value = "";
}, 5000);
},
error: function(error){
handleAlerts('danger', 'oops..something went wrong')
}
})
});
</script>
这是我要提交的表单。
【问题讨论】:
标签: jquery json django ajax django-forms