ajax结合form进行页面跳转

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)
# 错误信息显示在页面上
posted on 2019-08-13 17:23  帅的遭人砍see  阅读(681)  评论(0编辑  收藏  举报