您可以的Javascript做一个的XMLHttpRequest(https://developer.mozilla.org/en/using_xmlhttprequest)到POST输入框的文本(如果你使用jQuery的,在即将到来的例子更容易),并做一个DB查询服务器端查看电子邮件(输入框文本)是否是唯一的。因此,您将返回此视图的响应,其中针对非IE浏览器的@view_config()
修饰器中的xhr=True
以及针对IE浏览器设置的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)轻松地执行POST(客户端)来处理XMLHttpRequest。包括在你的模板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')
}
}
来源
2012-07-03 22:59:43
Raj
Thanks Wiz ...很高兴知道。我目前的做法是将电子邮件作为主键,然后捕获“除了IntegrityError:”错误,但我想也许有一种方法可以提前警告用户,因为超级烦人提交表单只是为了发现它失败。 – Lostsoul
实际上,您可以保存窗体的所有值,并为渲染器提供所有窗体的代码,以便在获取响应时允许窗体中正确填充的部分自动填充。 – Wiz
没有想到这一点,我会将它应用到我现有的代码中,但我仍然希望提供实时反馈(因为它适用于我的网站的许多其他区域)..但是,谢谢..我做到了想知道为什么我的表格一直空白,以及其他人如何保持价值。谢谢 – Lostsoul