【问题标题】:Flask with Fetch API and render_template - receive new rendered data带有 Fetch API 和 render_template 的 Flask - 接收新的渲染数据
【发布时间】:2018-06-26 01:14:05
【问题描述】:

在来自输入字段的Flask 项目中,我得到JS Fetch API 用户输入的值,然后我将其传递给我的Python 函数,根据用户输入我做不同的事情。

一切正常。 JavaScript 获得价值,Flask 看到了。

JS代码:

document.getElementById("search").addEventListener("click", function() {
    let token = new FormData();
    token.append('search', document.getElementById('search_place').value);
    const request = async() => {
        const response = await fetch('/stop', {
            method: 'POST',
            body: token,
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            mode: 'cors'
        }).then((tables) => {
            $('.table').html(tables);
        });
    };
    request();
});

使用 Flask 的每个用户输入,我都想更改模板中的内容:

return render_template('view.html', tables=[pd.DataFrame.to_html(df, index=False, justify='justify-all')])

因此,用户在“刷新”按钮单击后赋予新值,模板内的所有内容都应该是新的。

我不知道我应该如何接收来自 Flask 的 Fetch API 响应以及新的渲染数据。

我正在尝试:

.then((tables) => {
            $('.table').html(tables);
        });

没有任何成功。

提前致谢!

【问题讨论】:

  • const request = async() => { - 你在这里没有 return 任何东西......所以}).then((tables) => { tables 将在这里未定义......并且 fetch 通常就像 @ 987654330@
  • 嗯,谢谢你的回答!也许你想解释一下这个话题?
  • 嗯?你要我解释你的问题吗? here's some documentation for fetch api

标签: javascript python python-3.x flask fetch-api


【解决方案1】:
  • 您根本没有正确使用 fetch
  • 您正在请求中设置 cors 响应标头
  • mode: 'cors' 是跨源请求的默认值,但是
  • 你的请求是同源的,那你为什么要搞 CORS 什么
  • 无需创建该函数或使用异步等待

所以

document.getElementById("search").addEventListener("click", function() {
    let token = new FormData();
    token.append('search', document.getElementById('search_place').value);
    fetch('/stop', { method: 'POST', body: token })
    .then(response => response.text())
    .then(tables => $('.table').html(tables));
});

但如果你坚持使用 async/await

document.getElementById("search").addEventListener("click", async () => {
    const token = new FormData();
    token.append('search', document.getElementById('search_place').value);
    const response = await fetch('/stop', { method: 'POST',body: token} );
    const tables = await response.text();
    $('.table').html(tables));
});

【讨论】:

  • 对不起,有一个错字(在 => 中遗漏了一个 >)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多