javascript - 使用 Javascript 从 HTML 页面获取文本区域值到 Python Flask

标签 javascript html

我在弄清楚如何从 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 脚本时,文本区域和按钮都按其应有的样子存在,但是当我在文本区域中键入内容并单击按钮时,没有任何内容被打印。请帮忙。

最佳答案

你尝试走远路吗? 替换 $.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()" 就不是必需的了。

希望您觉得它有用,问候。

关于javascript - 使用 Javascript 从 HTML 页面获取文本区域值到 Python Flask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54578829/

相关文章:

两个对象的 JavaScript 函数 onclick

html - 输入范围值的指数增长

javascript - 如何在 html 5 中嵌入日历?

javascript - 通过 ajax 更改 css 属性不起作用?

Javascript 替换不起作用

javascript - 从对象数组中获取特定值以进行 html 注入(inject)

javascript - 使用 gulp-useref 如何添加额外文件?

javascript - 将 HTML 表单架构保存到 JSON

html - 避免元素在 "overflow: hidden"元素内时被截断

javascript - Html 和 JavaScript : How to return user input