在成功的ajax登录时打开一个新窗口

时间:2011-09-20 09:31:36

标签: php javascript html

在以下代码中,成功登录后,我尝试打开admin.htm。使用AJAX将内容加载到同一页面中,如何在新窗口中打开它,但在出现错误时在原始窗口中保留任何错误消息?

login.htm

 <form> 
    Username:<input type="text" name= "username" size="15" /> 
    Password:<input type="password" name= "passwrd" size="15" />
    <input name="submit" type = "button" onClick = "getdata('login.php','display',username.value,passwrd.value)"  value = "Login"  /> 
    </form>    

    <div id="display"></div>

login.js

function getdata(dataSource, divID, usrname, pwd) {
    if (xhr) {
        var obj = document.getElementById(divID);
        var requestbody = "username=" + encodeURIComponent(usrname) + "&password=" + encodeURIComponent(pwd);
        xhr.open("POST", dataSource, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                obj.innerHTML = xhr.responseText;
            }
        }
        xhr.send(requestbody);
    }
}

1 个答案:

答案 0 :(得分:1)

表单正在使用AJAX来显示您所在页面上的结果...

要在新页面中打开结果,请删除onclick和脚本并提供目标:

<form action="login.php" target="_blank" method="post"> 
Username:<input type="text" name= "username" size="15" /> 
Password:<input type="password" name= "passwrd" size="15" />
<input type="submit" value = "Login"  /> 
</form> 

如果您想要的只是在提交后没有看到表单,请将表单包装在显示div:

<div id="display">
  <form>.....
  </form>
</div>

<强>更新

to get the error message into the page, do 

if (xhr.readyState == 4 && xhr.status == 200) {
  var text = xhr.responseText;
  if (text.indexOf("You must") == 0) obj.innerHTML = text;
  else window.open(text,"_blank")
}

<?php
$usernam = $_POST["username"];
$pwd = $_POST["password"];
if (empty($usernam) || empty($pwd)) {
    echo "You must enter both username and password to login.";
} else {
    echo 'admin.htm';
}
?>