[英]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. 我在弄清楚如何从Javascript获取帖子到我的Python Flask服务器时遇到了麻烦。
Here's the important part of what I've got in my html file 这是我在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>
and here's what I've got in my Python flask file 这就是我的Python flask文件中的内容
@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. 当我运行python脚本时,textarea和按钮在应有的位置,但是当我键入textarea并单击按钮时,什么也不会打印。 Please help.
请帮忙。
You try with the long way? 你尝试很长的路要走吗? Replace
$.post('/postmethod', {text: textBox} );
替换
$.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. 这应该在页面上打印python代码的变量“ data”的内容。
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. 然后,就不需要
onClick="writeOut()"
。
I hope you find it useful, regards. 希望您觉得有用。
id's value should be in quotes id的值应该用引号引起来
<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 并且return false阻止页面重定向
sorry guys, I'm new to Javascript. 抱歉,我是Java新手。 Thank you very much!
非常感谢你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.