## AJAX向服务器发生请求步骤如下
1.创建XMLHttpRequest对象(旧版本的Internet Explorer(IE5和IE6)中使用 ActiveXObject 对象)
var xhr=new XMLHttpRequest();
2.向服务器发送请求,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
(1)准备发送请求
xhr.open(method,url,async);
method:请求的类型;GET 或 POST
url:请求的目标文件
async:true(异步)或 false(同步)
(2)执行发送动作
xhr.send(String);
string:仅用于 POST 请求GET请求用null;
3.回调函数onreadystatechange();
下面看代码理解一下ajax请求的用法和比较一下get和post两种请求方式的区别
(代码是判断输入的账号和密码是否正确)
<body>
<form>
账号:<input type="text" id="userN"><span id="error"></span><br>
密码:<input type="password" id="pw"><br>
<input type="button" value="提交" id="btn">
</form>
<script>
window.onload=function(){
var btn=document.getElementById('btn');
btn.onclick=function(){
var userN=document.getElementById('userN').value;
var pw=document.getElementById('pw').value;
// 创建请求对象(兼容处理)
if(window.XMLHttpRequest){
var xhr=new XMLHttpRequest();
}else{
var xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
var error=document.getElementById('error');
// 准备发送请求
xhr.open('get','loginTest.php?userN='+userN+'&pw='+pw,true);
// 发送请求
xhr.send(null);
// 回调函数
xhr.onreadystatechange=function(){
// 数据接收完毕
if(xhr.readyState==4){
if(xhr.status==200){
// 数据接收
var data=xhr.responseText;
if(data=='0'){
error.innerText='登录失败';
}else if(data=='1'){
error.innerText='登录成功';
}
}
}
}
}
}
</script>
</body>
loginTest.php代码如下
<?php
$userN=$_GET['userN'];
$pw=$_GET['pw'];
// 如果账号密码正确则返回1,否则放回0
if($userN==$pw){
echo '1';
}else{
echo '0';
}
?>
当用post方式请求时,需要在send()中加上要传递的数据,如:“userN=12&pw=12”。同时也要使用 setRequestHeader() 来添加 HTTP 头。
var para='userN='+userN+'&pw='+pw;
// 准备发送请求
xhr.open('post','loginTest.php',true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// 发送请求
xhr.send(para);
loginTest.php代码改变如下
<?php
//post方式获取数据
$userN=$_POST['userN'];
$pw=$_POST['pw'];
// 如果账号密码正确则返回1,否则放回0
if($userN==$pw){
echo '1';
}else{
echo '0';
}
?>