为什么ajax在屏幕上显示我0时,后端flask返回str(0)和str(2)值的函数?



你好,我正在开发一个OTP设备验证系统。它是如何工作的:用户输入他的凭据,如电话号码和密码,然后ajax从后端调用/signin函数,该函数验证凭据并检查用户设备是否受信任。如果用户设备是可信的,它只是返回到仪表板,它不信任它return str(0),如果凭据是错误的,那么str(2)。我想做的是javaScript处理这些后端返回值,如果设备不受信任,则显示OTP字段,手机,密码屏幕隐藏,如果返回值为2,则显示输入凭据的flash MSG并呈现index。html模板

我的代码

<div class="modal fade login_modal" id="signin" tabindex="-1" role="dialog"
aria-labelledby="myExtraLargeModalLabel" aria-modal="true">
<div class="modal-dialog modal-dialog-centered modal-md">
<div class="modal-content">
<a href="#" class="close_modal" data-dismiss="modal">✖</a>
<div class="login-content">
<h2> Sign In to your Account </h2>
<div class="form-holder">
<form method="POST" action="/signin">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input id="lmobileno" placeholder="Mobile Number" type="number" required
class="form-control" name="lmobileno">
<span class="absolute-label" for="lmobileno">Mobile Number</span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input id="password" placeholder="Password" type="password" required
class="form-control" name="password">
<span class="absolute-label" for="password">Password</span>
</div>
</div>
</div>
<div class="row" id="row_otp">
<div class="col-lg-12 animate__animated animate__fadeInLeft wow" data-wow-delay="0.3s">
<div class="form-group">
<input placeholder="OTP" id="otp" onchange="validateOTP()" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
maxlength="6" type="number" class="form-control" name="otp" pattern="^[0-9]{6,6}$" title="Enter OTP sent to you on your above given mobile number">
<label id="label_otp" class="absolute-label" for="otp">OTP</label>
<input id="otpbtn" type="button" class="btn btn-secondary btn-sm btn-resend-otp"  value="Didn't Receive an OTP? Click Here to Resend" onclick="resendFinjaOTP('mobileno',null);"/>
<div><span class="resend-text" id="time"></span></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 text-center">
<button type="submit" onclick="$('#overlay').fadeIn();" class="btn btn-primary"> Sign In </button>
<p> Don't have an account? <a href="/investor_sign_up#register"> Sign Up </a>
</p>
<p> Or <a href="/finja_sign_up">Sign Up </a> using your <a href="/finja_sign_up"> <img class="finja-signup-img"
src="https://finja.pk/assets/images/logo.svg" width="9%"> </a> account </p>
<p> <a href="/reset_password"> Forgot Password? </a> </p>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script src="../static/assets/js/header.js"></script>
<script>
$('#signin').ready(function(){
$('#otp').hide();
$('#otpbtn').hide();
$('#label_otp').hide();
});
function validatePassword() {
var mobile = $('#lmobileno').val();
var password = $('#password').val();
if (mobileno != 0 && password !=0) {
$('#overlay').fadeIn();
$.ajax({
type: "POST",
url: "/signin",
data : {lmobileno: mobile, password: password},
}).done(function (data) {
$('#overlay').fadeOut();
if (data == 0) {
$('#otp').show();
$('#lmobileno').hide();
$('#password').hide();
}
else if (data == 2) {
Swal.fire({
icon: 'error',
title: 'INVALID PASSWORD OR MOBILE NUMBER',
text: 'Sign in again',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
});
}
};


function validateOTP() {
const label_otp = document.getElementById('label_otp');
const row_mobileno = document.getElementById('row_mobileno');
const row_otp = document.getElementById('row_otp');
var str = document.forms["Form"]["otp"].value;
var n = str.length;
var otp = { otp: str };
if (n == 6) {
$('#overlay').fadeIn();
$.ajax({
type: "POST",
url: "/verify_otp",
contentType: 'application/json',
data: JSON.stringify(otp),
dataType: 'json'
}).done(function (data) {
$('#overlay').fadeOut();
if (data == 1) {
Swal.fire({
icon: 'success',
title: 'OTP Verified Successfully',
text: 'You can proceed to signup now',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
else if (data == 0) {
Swal.fire({
icon: 'error',
title: 'INVALID OTP',
text: 'Enter the OTP sent to you on your phone',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
});
}
};

</script>

登录后端代码

@accounts_blueprint.route('/signin', methods=['POST'])
@limiter.limit('10 per minute')
def signin_post():
mobileno = format_mobileno(request.form.get('lmobileno'))
password = request.form.get('password')
# retrieve user's data from database's user table
existing_user = sessiondb.query(User).filter(User.mobileno == mobileno).first()
# validate user's mobile number and password
if existing_user is None:
flash('Invalid Mobileno.', 'signin')
return redirect(url_for('main.index'))
elif existing_user.state.name != State.Active.name or existing_user.status.name != Status.Verified.name:
flash('Account is not verified yet.', 'notVerified')
return redirect(url_for('main.index'))
elif Hash.verify_password(existing_user.password, password):
user = sessiondb.query(User).filter(User.mobileno==mobileno).first()
verifyDevice = device_verified(user)
if verifyDevice == str(1):
login_user(existing_user)
add_last_login()
add_investor_status()
return redirect(url_for('dashboard_blueprint.dashboard'))        
else:
return str(0)
else:
return str(2)

我是javascript和ajax的新手,我得到一个白色的屏幕,上面写着0和2。

首先删除登录表单中的表单标签,然后将javascript函数替换为

function ValidatePassword() {
var mobileno = $('#lmobileno').val();
var password = $('#password').val();
if (validate_mobile(mobileno)==true && password != null) {
$('#overlay').fadeIn();
$.ajax({
type: "POST",
url: "/signin",
contentType: 'application/json',
data: JSON.stringify({
"lmobileno": mobileno,
"password": password
}),
dataType: 'json'
}).done(function (data) {
$('#overlay').fadeOut();
if (data == 1) {
$('#otp').show();
$('#lmobileno').hide();
$('#password').hide();
}
else if(data==2) {
$('#overlay').fadeOut();
Swal.fire({
icon: 'error',
title: 'Invalid password or phone number',
text: 'Sign in again',
width: 500,
showConfirmButton: false,
showCloseButton: true
})
}
});
}
};

我相信你正在使用python-flask,使用jsonify代替直接返回。

from flask import jsonify # import this in top

然后

return jsonify({"msg": "0"}) # do same for 1 and 2 as well

现在在前端像这样读

if(data.msg == 0)

最新更新