0

好的,这就是我所拥有的。我有这个投票系统,您可以在其中单击一个按钮,然后使用 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 脚本会运行,但它显然不会将我带到页面。

4

1 回答 1

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入门指南

于 2013-03-19T07:47:06.687 回答