首页 > Web开发 > 详细

ajax结合form进行页面跳转

时间:2019-08-13 20:18:14      阅读:56      评论:0      收藏:0      [点我收藏+]

html

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/ajax/" id="fm" method="post">
{% csrf_token %}
{% obj.as_p %}
<input type="button" value="Ajax提交" id="btn">
</form>

<script src="/static/jquery-3.1.1.js"></script>
<script>
$(function () {
$(‘#btn‘).click(function () {
$.ajax({
url:‘/ajax/‘,
type:‘POST‘,
data:$(‘#fm‘).serialize(),
dataTpye:‘JSON‘,
success:function (arg) {
if (arg.status==‘钱‘){
window.location.href="http://www.baidu.com"
}
print(arg);
}
})
})
})
</script>
</body>
</html>


views
class AjaxForm(forms.Form):
price=fields.IntegerField()#静态字段,当程序运行起来时就执行了,并且执行后就不变化了,数据源更新但是不会在数据源取数据
user_id=fields.IntegerField(
# widget=widgets.Select(choices=[(0,‘alex‘),(1,‘liu‘),(3,‘li‘)]),
# widget=widgets.Select(choices=models.UserInfo.objects.values_list(‘id‘,‘username‘))#第一次永远用不上
widget=widgets.Select()
)
def ajax(request):
if request.method==‘GET‘:
obj=AjaxForm()
return render(request,‘ajax.html‘,{‘obj‘:obj})
else:
ret={‘status‘:‘钱‘}
import json
obj=AjaxForm(request.POST)
if obj.is_valid():#obj.is_valid()做的验证
print(obj.cleaned_data)
# 跳转到百度
# return redirect(‘http://www.baidu.com‘)#这种直接跳转的方式用在ajax上没有用处
return HttpResponse(json.dumps(ret))
else:
print(obj.errors)
# 错误信息显示在页面上

ajax结合form进行页面跳转

原文:https://www.cnblogs.com/wenghao/p/11347242.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!