后端視圖代碼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>
