from django.shortcuts import render, HttpResponse
from django import forms
from django.forms import fields, widgets
import json
# Create your views here.
# views.py
class AjaxForm(forms.Form):
price = fields.IntegerField()
user_id = fields.IntegerField(
widget=(
widgets.Select(choices=[(0, '张三'), (1, '李四'), (2, '王五'), ])
)
)
def ajax(request):
if request.method == 'GET':
obj = AjaxForm()
return render(request, 'ajax.html', {'obj': obj})
else:
obj = AjaxForm(request.POST)
ret = {'status': None, 'message': None}
if obj.is_valid():
# print(obj.cleaned_data)
# return redirect('http://www.baidu.com') # 使用ajax提交,即使redirect,也不会跳转
ret['status'] = 'true'
else:
# print(obj.errors) # obj.errors 是一个django.forms.utils.ErrorDict对象,继承自dict(字典)数据类型,默认是ul
# obj.errors有很多方法 默认为as_ul() 还有 as_json() as_data() as_text()
ret['message'] = obj.errors.as_text()
return HttpResponse(json.dumps(ret)) # json.dumps() 只能对python中的基本数据类型进行处理
<!--前端-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id='fm'>
<span id="msg"></span>
{% csrf_token %}
{{ obj.as_p }}
<input type='button' value='提交' id='btn'>
</form>
<script src='/static/jquery.js'></script>
<script>
$(function()
{
$('#btn').click(function () {
$.ajax({
url: 'http://127.0.0.1:8000',
type: 'POST',
dataType: 'JSON',
data: $('#fm').serialize(),
success: function (arg) {
if (arg.status == 'true') {
window.location.href = 'http://www.baidu.com'
}else{
console.log(arg.message);
$("#msg").html(arg.message);
}
}
})
})
})
</script>
</body>
</html>