最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call flask function from form and display results on same page - Stack Overflow

programmeradmin1浏览0评论

I have a Flask application which has a page where the user can input a sentence. I want to take this user input and feed that into a Flask method which will perform some calculations on that sentence and then return the result (which is a string).

I would ideally like it to return on the same page, just underneath the form's submit button.

At the moment, I am trying to do this by using javascript. Here's what I have at the moment:

result.html

 <head>
     <script type=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/result_sentence',{
             sentence: $('textarea[name="sentence"]').val()}, function(data) {
              // do nothing
              document.getElementById('display').innerHTML = data.result;
      });
        return false;
      });

   </script>

    </head><body>
    <!-- The form where the user inputs --> 
        <div id="interactive" style="margin-top:50px">
           <textarea style="width:100%;" rows="3" name="sentence" placeholder="Enter your sentence"></textarea>
           <a href="#" id=test button type="submit" class="btn btn-lg btn-success"> Predict </a>
           <label> I predict.. </label>
           <p><span id='display'></span></p>
        </div>

app.py

@app.route('/result_sentence')
def result_sentence():
   sentence = flask.request.args.get('sentence')
   pred = getPrediction(sentence)
   return jsonify(result=pred)

Also, it should be noted that on the results.html, I have already called another Flask function which has redirected my Flask app to results.html and has displayed some charts.

So the main problem I am facing is that I am not sure why nothing happens when I click the button. To me it seems that when the button is clicked it should pass the sentence into the Flask function and perform the calculations. I've looked at a bunch of questions that were already posted here on StackOverflow such as this one: Flask - Calling python function on button OnClick event but they didnt really help me in this regard. I don't really see where it is going wrong so I would appreciate any insight or help with this.

Thanks!

EDIT: So it seems that the first problem is that the JS function doesnt get called at all when the button is clicked...

I have a Flask application which has a page where the user can input a sentence. I want to take this user input and feed that into a Flask method which will perform some calculations on that sentence and then return the result (which is a string).

I would ideally like it to return on the same page, just underneath the form's submit button.

At the moment, I am trying to do this by using javascript. Here's what I have at the moment:

result.html

 <head>
     <script type=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/result_sentence',{
             sentence: $('textarea[name="sentence"]').val()}, function(data) {
              // do nothing
              document.getElementById('display').innerHTML = data.result;
      });
        return false;
      });

   </script>

    </head><body>
    <!-- The form where the user inputs --> 
        <div id="interactive" style="margin-top:50px">
           <textarea style="width:100%;" rows="3" name="sentence" placeholder="Enter your sentence"></textarea>
           <a href="#" id=test button type="submit" class="btn btn-lg btn-success"> Predict </a>
           <label> I predict.. </label>
           <p><span id='display'></span></p>
        </div>

app.py

@app.route('/result_sentence')
def result_sentence():
   sentence = flask.request.args.get('sentence')
   pred = getPrediction(sentence)
   return jsonify(result=pred)

Also, it should be noted that on the results.html, I have already called another Flask function which has redirected my Flask app to results.html and has displayed some charts.

So the main problem I am facing is that I am not sure why nothing happens when I click the button. To me it seems that when the button is clicked it should pass the sentence into the Flask function and perform the calculations. I've looked at a bunch of questions that were already posted here on StackOverflow such as this one: Flask - Calling python function on button OnClick event but they didnt really help me in this regard. I don't really see where it is going wrong so I would appreciate any insight or help with this.

Thanks!

EDIT: So it seems that the first problem is that the JS function doesnt get called at all when the button is clicked...

Share Improve this question edited Apr 26, 2018 at 13:03 Rachel Solomon asked Apr 26, 2018 at 12:01 Rachel SolomonRachel Solomon 1772 silver badges13 bronze badges 2
  • 1 Is it sure that the JS-Function gets called if you press the button (maybe insert a console.log) to see if this is happing. Next: Is the flask route called? Insert a print-statement to make sure this happens. – MrLeeh Commented Apr 26, 2018 at 12:08
  • @MrLeeh the JS function doesnt get called with the bind('click'), but does get called when you add an "onclick=" to the button.. but then the flask route never gets called. – Rachel Solomon Commented Apr 26, 2018 at 12:16
Add a ment  | 

1 Answer 1

Reset to default 6

You need to use $.ajax with jquery. First, simply create an input box and button which, when clicked, will trigger the script to call the Ajax. In the HTML, the javascript will retrieve the user's input when the button is clicked, and the input will be sent to the flask route:

<html>
  <head>
    <script src="https://ajax.googleapis./ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
   <body>
     <input type='text' id='word'>
     <button type='button' id ='retrieve'>Submit</button>
     <div id='wordResult'></div>
   </body>
  <script>
    $(document).ready(function() {
       $('#retrieve').click(function(){
           var word = $('#word').val();
           $.ajax({
           url: "/get_word",
           type: "get",
           data: {word: word},
           success: function(response) {
           $("#wordResult").html(response.html);
          },
          error: function(xhr) {
            //Do Something to handle error
         }
         });
       });
    });
  </script>
</html>

Then, create the route in app.py:

@app.route('/get_word')
def get_prediction():
  word = flask.request.args.get('word')
  return flask.jsonify({'html':getPrediction(word)})
发布评论

评论列表(0)

  1. 暂无评论