简体   繁体   中英

Is it possible to $.post inside a $.get in jquery (Flask + Python)

I'm relatively new to Flask in Python. So please bear with me if my question sounds stupid.

I've a GET function like this below:

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

I've a text box (#transaction_year) on html and I'd need that input to be used within this above function (as a $.post). The above function is called by following JQuery


$('#get-transactions-btn').on('click', function (e) {
        $.get('/transactions', function (data) {
          ....
});
});

The problem is when the button (get-transactions-btn) is clicked, the function (get_transactions) runs as a GET and fetches data. Is it possible to do something like below to run $.post before $.get is executed and still have the value from the input text box (#transaction_year)?


$('#get-transactions-btn').on('click', function (e) {
        $.get('/transactions', function (data) {
          var transaction_year = $("#transaction_year").val();
          $.post("/transactions", { transaction_year: transaction_year })
          ....
});
});

So that I can use it within my function like below?

@app.route('/transactions', methods=['GET','POST'])
def get_transactions():
    # Store the value from post here
    transaction_year = float(request.form['transaction_year'])
    ...

Thank you and appreciate any feedback.

I've managed to get a workaround for this. I created a separate function to store the $.post value in a global variable input_year.

input_year = 1
@app.route('/transactions_input', methods=['POST'])
def get_transactions_input():
    global input_year
    transaction_year = float(request.form['transaction_year'])

    input_year = transaction_year

    return 'Done'

Updated JQuery to below:

 $('#get-transactions-btn').on('click', function (e) {
        var transaction_year = $("#transaction_year").val();
        $.post("/transactions_input", { transaction_year: transaction_year }) 
        $.get('/transactions', function (data) {
        ....
});
});

Global variable sets the input box value and this can be used inside /transactions .

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