您可以使用Javascript执行XMLHttpRequest ( https://developer.mozilla.org/en/using_xmlhttprequest )以POST输入框的文本(如果您使用jQuery 则更容易,如即将到来的示例所示)并执行数据库查询服务器端查看电子邮件(输入框文本)是否唯一。因此,您将从此视图返回响应,其中在非 IE 浏览器的装饰器中为 IE 浏览器设置。例如:xhr=True
@view_config()
request.response.content_type='text/html'
@view_config(permission='view', route_name='check_email', renderer='json') ##for IE browsers
@view_config(permission='view', route_name='check_email', renderer='json', xhr=True) ##for non-IE
def check_email(request):
email= request.POST['email']
dbquery = DBSession.query(User).filter(User.email==email).first()
## if the email exists in the DB
if dbquery:
msg = 'used'
## else if the email is available
else:
msg = 'available'
if request.is_xhr:
return {'msg':msg}
else: # for IE browser
request.response.content_type = 'text/html'
return Response(json.dumps({'msg':msg}))
您可以通过使用诸如 jQuery 之类的库来处理 XMLHttpRequest 轻松地(客户端)进行 POST。在您的模板中包含 jQuery 库以及脚本中的 .js 文件后:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src="{{request.static_url('tutorial:static/myscript.js')}}"></script>
然后在myscript.js中执行:
$(function() {
$('#email').on('blur', postEmail)
})
// this function POSTs the entered email
function postEmail() {
var email = $(this).val()
$.post('/check_email', email, callback)
}
// this function is used to do something with the response returned from your view
function callback(data) {
if (data['msg'] === 'used') {
alert('used')
}
else if (data['msg'] === 'available') {
alert('available')
}
}