原生Ajax发送get/post请求demo
- ajax发送请求的过程分为5步
1.创建异步对象
var xhr = new XMLHttpRequest();
2.配置请求信息(请求方式,请求url,同步或者异步标志位)同步或者异步标志位,默认是true表示异步,false表示同步
// get请求如果有参数就需要在url后面拼接参数,
// post如果有参数,就在请求体中传递
xhr.open('get','./check.php?username='+uname+'&password='+pw,true)
xhr.open("post","./check.php",true);
3.设置请求头(setRequestHeader())
// 1.get不需要设置
// 2.post需要设置请求头:Content-Type:application/x-www-form-urlencoded
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
application/x-www-form-urlencoded:窗体数据被编码为名称/值对,这是标准且默认的编码格式。
当action为get时候,客户端把form数据转换成一个字串append到url后面,用?分割。
当action为post时候,浏览器把form数据封装到http body中,然后发送到server。
4.设置请求体 send()
// 1.get的参数在url拼接了,所以不需要在这个函数中设置
// 2.post的参数在这个函数中设置(如果有参数)
xhr.send(null)
xhr.send("username="+uname+"&password="+pw);
5.让异步对象接收服务器的响应数据
// 一个成功的响应有两个条件:1.服务器成功响应了 2.异步对象的响应状态为4(数据解析完毕可以使用了)
//responseText 获得字符串形式的响应数据。
//responseXML 获得 XML 形式的响应数据。
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
var data = xhr.responseText;
}
- 原生Ajax-Demo----模拟用户校验
模拟发送用户名密码到后端校验,校验成功返回“1”,校验失败返回“2”
根据不同校验
s<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生Ajax</title>
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById('btn');
btn.onclick = function(){
var uname = document.getElementById('username').value;
var pw = document.getElementById('password').value;
// 使用Ajax发送请求需要如下几步:
// 1、创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();
// 2、准备发送
xhr.open('get','./check.php?username='+uname+'&password='+pw,true);
// 3、执行发送动作
xhr.send(null);
// 4、指定回调函数
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var data = xhr.responseText;
var info = document.getElementById('info');
if(data == '1'){
info.innerHTML = '登录成功';
}else if(data == '2'){
info.innerHTML = '用户名或者密码错误';
}
}
}
}
}
}
</script>
</head>
<body>
<form>
用户名:
<input type="text" name="username" id="username"><span id="info"></span>
<br> 密码:
<input type="text" name="password" id="password">
<input type="button" value="登录" id="btn">
</form>
</body>
</html>
- PHP代码
<?php
$uname = $_GET['username'];
$pw = $_GET['password'];
if($uname == 'admin' && $pw == '123'){
echo '1';
}else{
echo '2';
}
?>
- 运行结果