发生这种情况是因为当文档加载时,它会在找到脚本标记时停止。
在您的情况下,您正在尝试在文档的未确定部分中回显数据,当它已经加载时。
这是我的解决方案:
PHP 文件(test.php):
<?php
if(!isset($_POST['bldgName']) || !isset($_POST['netName']) {
die("false"); //returns false if the values are NOT set
} else {
die("true"); //returns true if the values are set
}
?>
在您的文件(file.html)中:
<form method="post" action="test.php" id="formtest">
<input type="text" name="bldgName" />
<input type="text" name="netName" />
</form>
<script type="text/javascript">
if(getAjaxResponse(document.getElementById("formtest") == "true") {
alert("Please complete the fields for Building Name or Network Name");
window.navigate("view_netbdlg.php");
}
function getAjaxResponse(frm){
var elem = frm.elements;
var params = "";
url = form.action;
for(var i = 0; i < elem.length; i++){
if (elem[i].tagName == "SELECT"){
params += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) + "&";
} else {
params += elem[i].name + "=" + encodeURIComponent(elem[i].value) + "&";
}
}
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
</script>