[英]Get textarea value from HTML page to Python Flask using Javascript
我在弄清楚如何從Javascript獲取帖子到我的Python Flask服務器時遇到了麻煩。
這是我在html文件中獲得的內容的重要部分
<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>
這就是我的Python flask文件中的內容
@app.route('/postmethod', methods = ['POST'])
def postmethod():
data = request.form['text']
print "Hello world!"
print data
return data
當我運行python腳本時,textarea和按鈕在應有的位置,但是當我鍵入textarea並單擊按鈕時,什么也不會打印。 請幫忙。
你嘗試很長的路要走嗎? 替換$.post('/postmethod', {text: textBox} );
對於
$.ajax({
method: "POST",
url: "postmethod", //here can be '/postmethod'
dataType: 'text',
data: {text: textBox},
success: function(result) {
// example
$('body').html(result)
}
});
這應該在頁面上打印python代碼的變量“ data”的內容。
另一件事,
我發現您使用兩種方式來提交按鈕,如果您使用
$('a#test').bind('click', function() { //code });
然后,就不需要onClick="writeOut()"
。
希望您覺得有用。
id的值應該用引號引起來
<a href="#" id="test">
<input type="button" value="submit" id="submit" onClick="writeOut()">
</a>
我發現的解決方案是添加
$(function() {
});
周圍
$(function() {
$('a#test').bind('click', function() {
var textBox = document.getElementById('targetTextArea').value;
$.post('/postmethod', {text: textBox} );
return false;
});
});
並且return false阻止頁面重定向
抱歉,我是Java新手。 非常感謝你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.