简体   繁体   English

@ app.route在没有重定向的情况下不起作用

[英]@app.route not working without redirection

This function is working perfectly if I do a redirect to another page @app.route('/results') but I'm struggling to make it work in the same page without reloading : 如果我重定向到另一个页面@ app.route('/ results'),则此功能可以正常工作,但是我正努力使其在同一页面上工作而不重新加载:

@app.route('/')
def static_file():
    return app.send_static_file('index.html')

@app.route('/')
def results():
    headers = {
        'X-ApiKey': 'xxxxxxxxxxxxxxxx',
    }

    data = {'data': request.args.get('data')}

    results = requests.post('https://apiv2.indico.io/personality', headers=headers, data=data)
    return results.text

I'd like to display the results of the api call in the same page (below the input box) 我想在同一页面(在输入框下方)显示api调用的结果

<form action="" onsubmit="return false";>
  <strong> Try It <br><br>
  </strong><br>
  <input type="text" name="data"><br><br>
        <input type="submit" onclick="showResults();">
        <label id:Results>Your Result: </label>
        <p><span id='display'></span></p>
    </form>

I've also added some JS: 我还添加了一些JS:

 <script language="JavaScript">
    function showResults() {
        document.getElementById('display').innerHTML = 
                    document.getElementById("Results").value;
    }
  </script>

What's wrong with my code? 我的代码有什么问题? I'm using Flask framework. 我正在使用Flask框架。

If I understood you correctly, what you want to achieve is to have RESTful API written in Flask microframework, which would allow you to obtain some results and display on your page without reloading. 如果我理解正确,那么您想要实现的是用Flask微框架编写RESTful API,这将使您获得一些结果并显示在页面上而无需重新加载。 If so, your approach is wrong. 如果是这样,您的方法是错误的。

Firstly, you can't route multiple functions with common URL: 首先,您不能使用通用网址来路由多个功能:

@app.route('/common_route')
def foo():
    pass
@app.route('/common_route')
def bar():
    pass

It is impossible to determine which function did you want to be invoked if you load http://yourwebsite/common_route . 如果加载http:// yourwebsite / common_route ,则无法确定要调用哪个函数。

In order to avoid page reloading, you should rather use Flask-RESTful module and implement an API for obtaining results. 为了避免页面重新加载,您应该使用Flask-RESTful模块并实现用于获取结果的API。

import flask-restful
class Results(Resource):
    def __init__(self):
        super(Results)
    #for GET requests
    def get(self):
        #your code here
        pass
    #for POST requests
    def post(self):
        #your code here
        pass

api = Api(app)
api.add_resource(Results(),'/api/results')

Then you can obtain your results fe with JS & jQuery code: https://www.w3schools.com/jquery/jquery_ajax_get_post.asp 然后,您可以使用JS和jQuery代码获得结果: https : //www.w3schools.com/jquery/jquery_ajax_get_post.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM