简体   繁体   中英

Get textarea value from HTML page to Python Flask using Javascript

I'm having a bit of trouble with figuring out how to get a post from Javascript to work, to my Python Flask server.

Here's the important part of what I've got in my html file

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js </script>
<script type=text/javascript>
    $('a#test').bind('click', function() {
        var textBox = document.getElementById('targetTextArea').value;
        $.post('/postmethod', {text: textBox} );
    });
</script>

<!--textarea-->
<textarea rows="1" cols="20" id="targetTextArea">
</textarea>

<!--button-->
<form method="post" role="form">
<a href=# id=test>
    <input type="button" value="submit" id="submit" onClick="writeOut()">
</a>
</form>

and here's what I've got in my Python flask file

@app.route('/postmethod', methods = ['POST'])
def postmethod():
    data = request.form['text']
    print "Hello world!"
    print data
    return data

When I run my python script the textarea and button are there as they should be, but when I type into the textarea and click the button nothing is printed. Please help.

You try with the long way? Replace $.post('/postmethod', {text: textBox} ); for

$.ajax({
        method: "POST",
        url: "postmethod", //here can be '/postmethod'
        dataType: 'text',
        data: {text: textBox},
        success: function(result) {
            // example
            $('body').html(result)
        }
});

This should print on page the content of the variable "data" of python code.

Another thing,

I see that you are using two ways for the submit button, if you use

$('a#test').bind('click', function() { //code });

then, the onClick="writeOut()" is not neccessary.

I hope you find it useful, regards.

id's value should be in quotes

<a href="#" id="test">
        <input type="button" value="submit" id="submit" onClick="writeOut()">
    </a>

The solution I found was to add

$(function() {
});

around it

$(function() {
    $('a#test').bind('click', function() {
        var textBox = document.getElementById('targetTextArea').value;
        $.post('/postmethod', {text: textBox} );
        return false;
    });
});

and also the return false prevents the page of redirecting

sorry guys, I'm new to Javascript. Thank you very much!

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