这是我的观点:
def planning(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('loginregistration.views.login'))
if request.is_ajax:
POST = request.POST
msg = "Success"
print request.POST
return HttpResponse(msg)
else:
form = planForm()
return render(request, 'plan.html', {'form':form})
这是我的 html:
{% extends "base.html" %}
{% block title %}Plan{% endblock %}
{% block content %}
<a>Welcome to planning</a>
{{form.as_p}}
<script>
<----- I need to know how to set this up ---->
</script>
{% endblock %}
我知道我需要制作一个按钮,单击该按钮即可提交我的表单,但从我在互联网上看到的示例来看,它不是很直观。有人可以给我举个例子,我如何在此页面上获得一个按钮来将 ajax 调用发送到服务器。
编辑: 我如何将其连接到按钮?
{% extends "base.html" %}
{% block title %}Plan{% endblock %}
{% block content %}
<a>Welcome to planning</a>
{{form.as_p}}
<button id="form_submit">Submit</button>
<script>
$('button#form_submit').click(function() {
$.ajax({
type: "POST",
url:"/planning/submit/",
data: {
'test': 'success',
},
success: function(){
alert('test')
},
error: function(){
alert("Error");
});
</script>
{% endblock %}
最佳答案
有很多方法可以实现这一点,但这里有一个,请记住,您对 <form>
没有太多控制权。属性:
你会制作一个像这样的按钮:
<button id="form_submit">Submit</button>
然后,在<script>
内标签,类似(使用一些 jQuery):
$('button#form_submit').click(function() {
$.ajax({
type: "POST",
url:"/planning/submit/",
data: $("#form_id").serialize(),
success: function(){
alert('test')
},
error: function(){
alert("Error");
});
});
看起来您刚刚错过了最后一个 });
,并且您应该序列化表单数据以发送它(将 form_id
替换为您的表单 ID)。
关于javascript - Ajax、jQuery、Django。这是如何设置的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337622/