您可以的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