你可以使用 AJAX 来做这件事。当您不想重新加载页面以在 HTML 页面的特定位置或 Div 中执行任务时,AJAX 非常适合此类问题。
对于您的问题,您需要创建一个包含表单的 HTML 文件,然后通过 AJAX 提交。并通过相同的 AJAX 获得您的响应。
<script type="text/javascript">
function submit_ajax(val1,val2,param1,param2,subfile){
var http = new XMLHttpRequest();
var url = subfile;
var params = val1+"="+param1+"&"+val2+"="+param2;
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
//Remove the alert and use whatever you want to do with http.responsetext like
// document.getElementById("YourDiv").innerHTML=document.getElementById("YourDiv").innerHTML +http.responsetext
}
}
http.send(params);
}
</script>
</head>
<body>
<form>
<input type="text" id="user" value="user" name="user" />
<input type="password" id="password" value="pass" name="pass" />
<button onclick="submit_ajax(user.name,password.name,user.value,password.value, "submit_file.php");">Submit</button>
</form>
<div id="YourDiv">
<!--Something appears here after callback-->
</div>
这是第一页。现在根据需要在您的 PHP 文件(可能是 submit_file.php)中使用您的脚本,然后通过验证或其他方式在您的 div 中回显您想要的文本.. 示例将是
<?php
$username=$_POST['user'];
$password=$_POST['pass'];
if(validateuser($username,$password)){
if(checkuserpass($username,$password){
echo "You were successfully logged in!";
}
echo "Sorry Username/Password Mismatch";
}
else {
echo "There was an error in your input!Please Correct";
}
?>
希望你得到你想要的......