后端视图代码views.py
from form_registration import RegistrationForm
def check_user(): form = RegistrationForm() # 定义json字典数据格式 result = { "code":"", "data":"" } user_lst = [i for i in User_db().keys()] print(user_lst) if request.method == 'GET': return render_template('register.html', form=form) if form.validate_on_submit(): username = request.form.get("username") print(username) # 查询数据库有无这个用户 if username in user_lst: result["code"] = 400 result["data"] = "用户名已存在" else: result["code"] = 200 result["data"] = "用户名未被注册,可以使用" # return jsonify(result) return render_template('register.html', error=result, form=form)
register.html 模板里加
{% if error %}
<p id="error" class="text-danger">{{ error.data }}</p>
{% endif %}
javascripts代码
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script> //使用jQuery,获取用户名输入框信息,触发焦点事件 // {#校验用户名#} $("#username").blur( function () { var username = $("#username").val(); var url = "/check_user/"; var send_data = { "username": username, }; $.ajax( { url: url, type: "post", data: send_data, success: function (data) { if (data.code == 400){ $("#submit").attr("disabled",true) } else{ $("#submit").attr("disabled",false) } {#$("#error").text(error.data)#} var error = data['error']; $("#error").html(error); $("#error").show(); }, error: function (error) { console.log(error) } } ) } ) </script>