有人可以帮助我在Django中使用AJAX吗?我正在尝试创建一个具有2个输入的简单表单,并将其发送到我的python后端,而无需刷新页面。这是我的AJAX代码:
<script type="text/javascript">
$(document).ready(function(){
$("#seearch").submit(function(e){
e.preventDefault()
$.ajax({
type:'POST',
url:'/some/',
data:{
origin:$('#origin').val(),
destination:$('#destination').val(),
},
success:function(){
document.write("HelloWorld")
}
});
return false;
});
});
</script>
这是我用于表单的代码:
<div style = "
width:0.01px;
height:0.01px;
position:relative;
top:-700px;
left:0px;">
<div class="container px-5 py-24 mx-auto flex flex-wrap items-center" >
<form id="seearch">
<input id="origin" class="button" name="origin" placeholder="Where from?" type="text"><div></div>
<input id="destination" class="button" name="destination" placeholder="Where to?" type="text">
<input class="button" name="navigate" type="submit" placeholder="navigate">
</form>
</div>
</div>
发送到后端的请求应该是AJAX请求,但是几乎就像表单忽略了AJAX代码一样。当我单击提交时,它只是简单地提交表单并刷新页面。 我已经为此苦苦挣扎了将近2天,如果有什么可以帮助我弄清楚我哪里出错了,那将是一个很大的帮助。谢谢!
答案 0 :(得分:-1)
您的提交按钮的类型为=“ submit”。因此它将尝试按照“ html表单属性”重新加载页面。
所以您有2个选择:
将type =“ submit”更改为type =“ button”。因此,该表格将不会自动提交。 但是此解决方案的问题是,您的其他表单属性(如必填项和其他内容)将无法正常工作。
更合适的解决方案是:
JavaScript部分:
function mySubmitFunction(e) {
e.preventDefault();
------ ajax--------
}
选择适合您问题的选项。