ajaxrequest.打开被取消窗口.位置.href

ajaxrequest.open getting cancelled by window.location.href

本文关键字:窗口 位置 href 取消 ajaxrequest      更新时间:2023-09-26

好的,这是我得到的。我有这个投票系统,你点击一个按钮,它发送一个文本字段到php脚本使用ajaxrequest.open()。在它将数据发送到php脚本后,我希望它加载一个新页面。以下是我的(精简版)

var mytext = document.getElementById('textfield').value;
ajaxRequest.open("GET", "vote.php?mytext="+mytext, true);
ajaxRequest.send(null); 
window.location.href = "thanksforvoting.htm";

因此它将文本字段发送给vote.php -只有当我取出window.location.href line时才有效。只要这一行还在,它就不会做ajaxrequest。我想也许它正在取消,因为它正在加载另一个页面。

我想也许我可以使用php 'header'命令,但这似乎不起作用。它不会把我带到那页。上面的脚本将我带到页面,但它没有到达php脚本。如果我取出window。location。href php脚本会运行但显然不会跳转到页面

由于ajax请求是异步发出的,因此需要使用回调,否则重定向将在请求完成之前发生。在您的例子中,应该是这样的:

var mytext = document.getElementById('textfield').value;
ajaxRequest.onreadystatechange = callback;
ajaxRequest.open("GET", "vote.php?mytext=" + encodeURIComponent(mytext), true);
ajaxRequest.send(null); 
function callback() {
   if (ajaxRequest.readyState === 4 && ajaxRequest.status === 200) {
      window.location.href = "thanksforvoting.htm";
   }
}

MDN有一个很好的Ajax入门指南