【问题标题】:Flask page not refreshing in the browser after xmlHttpRequest() sendxmlHttpRequest() 发送后,Flask 页面未在浏览器中刷新
【发布时间】:2022-11-11 02:25:49
【问题描述】:

我正在使用事件侦听器来拦截表单提交,等待确认,然后使用 xmlHttpRequest 提交表单。我的页面的 POST 似乎正在工作(这意味着我可以检测到我期望的所有表单字段)但是,在 Flask 视图处理程序代码的末尾,重定向不会导致浏览器刷新页面。在视图处理程序中,我尝试使用 return redirect('/pagename') 重定向页面

我的事件侦听器处理程序代码中的积极结果是:

  // The positive action was chosen
  .then(() => {
    url = event.submitter.formAction
    submit_element = event.submitter;
    len = event.srcElement.length
    const formData = new FormData();
  
    for (i = 0; i < len; i++) {
      formData.append(event.srcElement[i].name, event.srcElement[i].value )
    }
    
    const request = new XMLHttpRequest();
    request.open("POST", url, true);
    request.send(formData);

  })

在我的烧瓶应用程序中,我还有:

@app.after_request
def after_request(response):
    """Ensure responses aren't cached"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    response.headers['Cache-Control'] = 'public, max-age=0'
    return response

如果我不使用事件侦听器拦截表单提交,那么表单提交和页面重定向将按预期工作。

我还需要在我的 xmlHttpRequest.send() 调用中包含其他内容以完全模拟表单提交吗?任何关于这里可能发生的事情的想法都非常感谢。

【问题讨论】:

  • XMLHttpRequest 被发明用于在不重新加载页面的情况下从服务器获取数据 - 它从不刷新页面。它只从服务器获取数据,但您必须自己重新加载页面。您可以尝试使用document.location = '/pagename',但它会再次加载页面(没有XMLHttpRequest)。因此,如果您想重新加载页面,则可以使用普通的form 和普通的redirect(),而不使用XMLHttpRequest。或者您应该从服务器获取数据并替换为HTML
  • 谢谢@furas - 我不认为我对 XMLHttpRequest 表示赞赏。即使我们在请求中使用 POST 方法将数据发送到服务器,您是否希望页面不会重新加载?当您建议使用document.location = '/pagename' 重新加载页面时,这对我来说是可行的。我会在哪里添加它?我可以检测 XMLHttpRequest 何时完成并在我的事件侦听器代码中重新加载页面吗?
  • XMLHttpRequest 是为了在不重新加载的情况下获取数据而创建的——所以我希望该页面不会被重新加载。 XMLHttpRequest 有一些方法可以检测 POST 是否完成 - 但 XMLHttpRequest 是旧方法,我不记得该怎么做。我更喜欢现代的fetch(url,...).then(data=&gt;{...}).catch(error=&gt;{...})。请参阅有关 Fetch 的 Mozilla 文档

标签: javascript python flask


【解决方案1】:

使用 JavaScript fetch() 而不是 XMLHttpRequest() 为我解决了我的问题。 fetch() 函数发布数据,我可以使用 .then() 子句重定向到 fetch() 之后的位置。

我能够使用如下代码发布表单提交中的所有字段,并被我的事件侦听器拦截;然后强制重新加载提交表单的页面。

              .
              .
// get url of submitting page
url = event.submitter.formAction;

// work out how many fields we have
len = event.srcElement.length;

// add each field to a formData object
const formData = new FormData();
for (i = 0; i < len; i++) {
  formData.append(event.srcElement[i].name, event.srcElement[i].value );
}

// post the data
response = fetch(url,
{
    body: formData,
    method: "post"
});    

response.then(response => {
  console.log(response);
  // reload the page
  document.location = response.url;

              .
              .

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2020-08-12
  • 2011-09-14
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
相关资源
最近更新 更多