我正在尝试使用一个小ajax来创建一个登录表单。当用户填写了错误的密码/用户名组合时,错误消息会被添加到带有sijax的页面:
这是我的两种方法:
1) Sijax方法
@staticmethod
def login(obj_response, uname, password):
# Verify the user.
username = uname.strip()
password = password.strip()
user = User.query.filter_by(username = username).first()
if user is None:
error = 'Invalid username/password combination'
elif password != user.password:
error = 'Invalid username/password combination'
# Log the user in if the info is correct.
else:
login_user(user)
session['logged_in'] = True
obj_response.redirect(url_for('user_home'))
# Clear the previous error message.
obj_response.script("$('#errormessage').remove();")
# Add an error message to the html if there is an error.
obj_response.html_append(".loginform", "<h4 id='errormessage'>" + error + "</h4>") 2) python方法:
@app.route('/login', methods=['GET', 'POST'])
def login():
if g.sijax.is_sijax_request:
# The request looks like a valid Sijax request
# Let's register the handlers and tell Sijax to process it
g.sijax.register_object(SijaxHandler)
return g.sijax.process_request()
return render_template('login.html')我想知道的是检查用户名/密码组合是否正确,如果不正确,则使用ajax显示错误消息,如果正确,则将用户重定向到其主页(url_for('userhome'))。
我试着用sijax method:obj_response.redirect(url_for('user_home'))知道,但这不起作用。
有什么想法吗?
我得到这个错误: obj_response.html_append(".loginform","“+ error + "") UnboundLocalError:赋值前引用的局部变量'error‘
发布于 2012-12-23 21:35:31
问题是您总是使用error,但只有在出现错误时才定义它。
简单的解决方案:在if user is None:行之前添加error = None。除此之外,仅在出现错误的情况下创建错误消息元素:
if error:
obj_response.html_append(".loginform", "<h4 id='errormessage'>" + error + "</h4>") https://stackoverflow.com/questions/14011367
复制相似问题