Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

html - Simple Flask jQuery AJAX

I am trying to get the logic of using jQuery AJAX and Flask, however I am not coming right. I have been following tutorials here and here, but no resolution. To get the logic - I simply want to input dates in two separate fields, and return those dates to the same page in a normal <p> tag. My suspicion is a problem in the server receiving the dates. Submitting the relative form does not return anything to #result

HTML FORM

<form>
    <input name="StartDate" id="StartDate" type="date" class="form-control"></div>
    <input name="EndDate" id="EndDate" type="date" class="form-control"></div>
    <a href="#" id="generate"><button class='btn btn-info'>Generate</button></a>
</form>
<p id=result></p>

jQuery - located at the bottom of the <body> tag, after importing jQuery itself.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('a#generate').bind('click', function () {
            $.getJSON($SCRIPT_ROOT + '/generate_report', {
                StartDate: $('input[name="StartDate"]').val(),
                EndDate: $('input[name="EndDate"]').val()
            }, function (data) {
               $("#result").text(data.result);
            });
            return false;
        });
    });
</script>

Flask Server - I have imported relevant dependencies

@app.route('/generate_report', methods=['GET', 'POST'])
def generate_report():

    start_date = request.args.get('StartDate', 0, type=str)
    end_date = request.args.get('EndDate', 0, type=str)
    
    return jsonify(result=start_date + "-" + end_date)
question from:https://stackoverflow.com/questions/66060275/simple-flask-jquery-ajax

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Please use the button to send the form, an anchor within the form does not make sense.

I would advise you to use the "submit" event of the form, although the "click" event of the button would also work. The preventDefault function bypasses the standard behavior of the form, so that you can send the form yourself using getJSON. To serialize the form data, I use the serialize function which converts all form data into a conforming string. Thus the data is sent as "application/x-www-form-urlencoded".

The variable $SCRIPT_ROOT is not used by me in this example because it is basically empty under localhost and is not absolutely necessary.

<form name="my-form">
  <div class="form-group">
    <label for="start-date">Start</label>
    <input type="date" name="start-date" id="start-date" class="form-control">
  </div>
  <div class="form-group">
    <label for="end-date">End</label>
    <input type="date" name="end-date" id="end-date" class="form-control">
  </div>
  <button type="submit" class="btn btn-primary">Generate</button>
</form>
<p id=result></p>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
      $("form[name='my-form']").submit(function(event) {
        event.preventDefault();
        const formData = $(this).serialize();
        $.getJSON("/generate_report", formData, function(data) {
          $("#result").text(data.result);
        });
      });
    });
</script>

The result of request.args.get is by default of type str. If the form field is empty, get always returns None. A possible KeyError due to a missing value is bypassed.

@app.route('/generate_report')
def generate_report():
    start_date = request.args.get('start-date')
    end_date = request.args.get('end-date')
    return jsonify(result=f'{start_date} - {end_date}')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...