Ajax实现form表单的POST请求,实现无刷新即可登录
前端为form.html,后端为form.php
代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax实现post请求</title>
<script type="text/javascript">
window.onload=function(){
var form=document.getElementsByTagName('form')[0];
form.onsubmit=function(){
//1.收集信息
var username=document.getElementById('username').value;
var password=document.getElementById('password').value;
//2.ajax提交信息
var xhr=new XMLHttpRequest();
var info="username="+username+"&password="+password;
xhr.onreadystatechange=function(){
if (xhr.readyState==4) {
//alert(xhr.responseText);
document.getElementById('result').innerHTML=xhr.responseText;
}
}
xhr.open('post','./form.php');
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.send(info);
return false;//阻止form表单的提交
}
}
</script>
</head>
<body>
<h2>form表单post提交</h2>
<form>
<p>用户名:<input type="text" name="username" id="username"></p>
<p>密码:<input type="password" name="password" id="password" ></p>
<p><input type="submit" value="注册" ></p>
</form>
<div id="result"></div>
</body>
</html>
接收页面form.php
这个,就比较简单啦
<?php
echo "hello:".$_POST['username'];
?>
附加图片
post
网友评论