ajaxrequest.open被window.location.href取消

时间:2013-03-19 07:43:10

标签: php javascript ajax

好的,这就是我所拥有的。我有这个投票系统,你点击一个按钮,它使用ajaxrequest.open()将文本字段发送到PHP脚本。在将数据发送到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行时才有效。只要该行在,它就不会执行ajaxrequest。我想也许它正在取消,因为它正在加载另一页。

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

1 个答案:

答案 0 :(得分:1)

由于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上有一个很好的getting started guide