javascript - 即使在 Flask WebApp 中状态为 200 后也无法打开页面

标签 javascript python ajax flask

我目前正在使用 Flask 构建一个网络应用程序,我已经制作了主页,您需要在其中输入电话号码和密码,这将获取这些凭据并向您发送所提供的电话号码上的 OTP。

理想情况下,填写凭据后单击注册按钮应该打开login.html,但事实并非如此。即使它能够 AJAX 调用并将电话号码发送到 @app.route('/verify',methods=['GET','POST']) 但 login.html 不会呈现。

Python 代码 - app.py

from flask import Flask, render_template, request, jsonify, redirect
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from wtosmsm import sendPostRequest
from emailSend import sendMail
from flask_cors import CORS
from random import randint
import requests
import smtplib
import json

app = Flask(__name__)
CORS(app)

#making the routes for different pages
#home route
@app.route('/')
def home_page():
    return render_template('home.html')

@app.route('/verify', methods=['GET','POST'])
def verify():
    response = request.get_data()
    print response
    #Credentials for sending an OTP on mobile number
    # if response != '':
    #   URL = 'https://www.way2sms.com/api/v1/sendCampaign'
    #   mobile_number = response.split('"')[3]
    #   otp_number = randint(100000,999999)
    #   message = str(otp_number) + ' is your OTP for registering at Scorecard Tech'
    #   response = sendPostRequest(URL, 'YRN1XLE4BMNUQYX85JGVEK0KDBB97CQV', '687MS1NRF2HV470G', 'stage', mobile_number, 'active-sender-id', message)
    #   print('otp sent')

    print 'This is working'
    return render_template('login.html')

# @app.route('/login', methods=['GET','POST'])
# def login():
#   return render_template('login.html')

if __name__ == '__main__':
    app.run(debug=True)

home.html -

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ScoreTech</title>
    <link rel="stylesheet" type="text/css" href="../static/css/mainone.css">
</head>
<body>
    <div class="wrapper">
        <div class="signup_card">
            <h2>Sign Up</h2>
            <div class="signup_form">
                <form class="signup_form_inner">
                    <input class="user_info" id="user_credential" type="text" name="username" placeholder="Email id/mobile number"><!-- <span class="alert_info" id="email_span">invalid number</span> -->
                    <input class="user_info" id="user_password" type="password" name="password" placeholder="Password">
                    <!-- <span class="alert_info" id="password_span">invalid password</span> -->
                    <button type="button" style="background-color:green;color:white;width: 50%;height:30px;border:none;border-radius: 30px;display:block;margin: 0 auto;padding: 5px; font-size: 15px;" onclick="sendOTP()">Sign Up</button>
                </form>
            </div>

            <center>
                <p class="bottom_text">Already have an account?
                    <a href="#">Login</a>
                </p>
            </center>           
        </div>

        <img class="home_img" src="../static/images/school.jpg" alt="home_image">

        <script type="text/javascript" src="../static/js/main.js?11"></script>
        <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </div>
</body>
</html>

main.js -

//Utility functions 
function testString(s) {
  if(s.length > 8){return true;}
  return false;
}

//basic functions 
function sendOTP(){
    var user_number   = $("#user_credential").val();
    var user_password = $("#user_password").val();
    if(testString(user_password)){
        $.ajax({
            url: "http://localhost:5000/verify",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({"message": user_number})
        }).done(function(data) {
            console.log(data);
        });
    }
    else{
        alert('Password not valid')
    }
}

终端上的输出 -

127.0.0.1 - - [20/May/2019 14:36:42] "GET / HTTP/1.1" 200 -
{"message":"9993776456"}
This is working
127.0.0.1 - - [20/May/2019 14:36:44] "POST /verify HTTP/1.1" 200 -

最佳答案

您可以使用Jquery加载功能渲染login.html文件。

Python 代码 - app.py

from flask import jsonify
#...
@app.route('/verify', methods=['GET','POST'])
def verify():
    response = request.get_data()
    print response
    print 'This is working'

    rep = {"valid": 1}
    return jsonify(rep)

@app.route('/render-login')
def render_login_page():
    return render_template('login.html')
#...

main.js-

//basic functions 
function sendOTP(){
    var user_number   = $("#user_credential").val();
    var user_password = $("#user_password").val();
    if(testString(user_password)){
        $.ajax({
            url: "http://localhost:5000/verify",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({"message": user_number})
            success:function(response) {

                console.log(JSON.stringify(response))
                if(response['valid'] == 1) {
                    window.history.pushState("", "", '/render-login');
                    $("body").load('/render-login')
                }
        }).done(function(data) {
            console.log(data);
        });
    }
    else{
        alert('Password not valid')
    }
}

编辑:另一种可能的解决方案:

您可以使用 $("body").html(response) 将当前的 html 文件替换为从服务器接收到的 login.html 文件。

Python 代码 - app.py

    #...    
    @app.route('/verify', methods=['GET','POST'])
    def verify():
        response = request.get_data()
        print response
        print 'This is working'

        return render_template('login.html')

    #...

main.js-

    //basic functions 
    function sendOTP(){
        var user_number   = $("#user_credential").val();
        var user_password = $("#user_password").val();
        if(testString(user_password)){
            $.ajax({
                url: "http://localhost:5000/verify",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({"message": user_number})
                success:function(response) {
                    /* if you did not want change the url in navigator,
                    uncomment window.history.pushState */
                    window.history.pushState("", "", '/render-login');
                    $("body").html(response)
            }).done(function(data) {
                console.log(data);
            });
        }
        else{
            alert('Password not valid')
        }
    }

关于javascript - 即使在 Flask WebApp 中状态为 200 后也无法打开页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217780/

相关文章:

javascript - 基于简单 iframe 的 AJAX 脚本 : first call yields 'null' element, 后续调用工作完美。我在这里不明白什么?

python - 两个 "np.longdouble"的总和产生很大的数值错误

jquery - 浏览器可以处理的json对象的大小有限制吗?

javascript - 从 asp.net 中的 Web 服务绑定(bind)失败

jquery - 为什么需要 jQuery AJAX #then 或 #done 或 #fail 方法?

javascript - 在运行嵌套查询的嵌套对象上使用 firebase 云函数搜索数据时未指定索引

javascript - 这段代码使用 typeof … != "undefined"和clearInterval 做什么?

javascript - 使用 JSON 数据填充选择选项

python - 更改应用程序和任务栏图标 - Python/Tkinter

python - 在一个巨大的字符串文件中查找一个字符串