简体   繁体   中英

Python Flask: send variable data to textarea on the same html page w/ JQuery

I have a one-page simple web project which gets data from 1 textarea, processes it and needs to output result on the same page inside another textarea.

I've tried following How to post the output result on the same page in flask app? , but I actually suck at js ( especially jquery :) ), so my server throws 400 BAD REQUEST.

handle_data() of app.py

@app.route("/", methods=['GET', 'POST'])
def handle_data():
    if request.method == 'POST':
        holder = Submission(request.form['submitText']) 
        it = holder.res.splitlines()

        for line in range(len(it)):
            global tst
            if "What kind of submission is this?" in it[line]:
                if "Sold Property" in it[line+1]:
                    tst = Sale(request.form['submitText'])
                    return jsonify(tst=tst)
                elif "Financed" in it[line+1]:
                    tst = Loan(request.form['submitText'])
                    return jsonify(tst=tst)
                else:
                    tst = Lease(request.form['submitText'])
                    return jsonify(tst=tst)

    return render_template("index.html")

index.html

<button class="bigButton" id="sendSub">START</button>

    <div class="textAreaCont">
        <form action="" method="POST" id="sub_form">
            <textarea rows="4" cols="50" class="textArea" id="submitText"></textarea>
            <button class="smallButton" id="clearButton">CLEAR</button>
        </form>
    </div>

    <div class="textAreaCont">
        <textarea rows="4" cols="50" class="textArea" id="getText" readonly></textarea>
        <button class="smallButton" id="saveAsButton">SAVE AS</button>
        <button class="smallButton" id="copyButton">COPY</button>
    </div>

script.js

$(document).ready(function(){
    $("#sendSub").click(function(){
        var $isEmpty = $("#submitText").val();
        if($isEmpty != ""){
        // somehow tell handle_data() it's POST request and throw the result of handle_data() inside #getText textarea
        }

Appreciate all the help!

It should be something like this but make sure you read correctly the json data in javascript.

$(document).ready(function(){
    $("#sendSub").click(function(){
        var isEmpty = $("#submitText").val();
        if(isEmpty != ""){
            $.ajax({
                url: '/',
                data: {'csrfmiddlewaretoken': '{{ csrf_token }}'}
                success: function (data) {
                    $('#getText').val(data);  # the data returned from your view
                }
          });
        }
    });
}):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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