2013-03-19 111 views
0

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

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的'头'命令,但似乎并没有工作。它没有把我带到页面。上面的脚本把我带到了页面,但它没有到达php脚本。如果我拿出window.location.href php脚本运行,但它显然不会带我到页面。

+2

您可以等待AJAX​​完成,然后更改窗口位置。 – 2013-03-19 07:46:06

+0

告诉标题错误。 – itachi 2013-03-19 07:48:12

+0

您也可以发表投票并加载新页面,这将是最直接的事情 – James 2013-03-19 08:40:47

回答

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对阿贾克斯的好getting started guide

+0

这似乎并不适用于我。我对javascript/ajax很陌生,这是我需要工作的唯一东西,所以我可能不会学到太多东西。我可以将回调函数放在同一个