
总的来说,ajax可以实现网页的局部更新,这是很棒的一个作用
ajax中get方式的使用 var oBtn = document.getElementsByTagName('button')[0];
// 1.创建初始值
var xhr;
// 解决兼容问题
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
// 2.创建请求·
xhr.open('get', 'text.json', true);
// 3.发送请求
xhr.send();
// 4.响应
// onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
// readyState 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
xhr.onreadystatechange = function () { // 每当 readyState 属性改变时,就会调用该函数
oBtn.onclick = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var obj = JSON.parse(xhr.responseText);
// console.log(obj);
document.getElementById('user').innerText = obj.user;
document.getElementById('age').innerText = obj.age;
}
}
}
ajax中post方式的使用
html代码
<input type="text" id="use"><br>
<input type="password" id="psw"><br>
<button id="login">登录</button>
js代码
// 获取元素
var useName = document.getElementById('use');
var oPsw = document.getElementById('psw');
var oLogin = document.getElementById('login');
oLogin.onclick = function () {
// 创建初始值
var xhr;
// 解决兼容问题
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); // 适合大部分浏览器
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP'); // 针对IE5、IE6
}
// 创建请求
xhr.open('post', 'http://146.56.207.108:3011/Handler/UserHandler?action=login', true);
// 先设置请求头
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// 发送请求
xhr.send("userName=" + useName.value + "&password=" + oPsw.value);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// JSON.parse() 方法能将对象格式的字符串,转换为对象
// JSON.stringify()方法能将对象格式转换为字符串格式
console.log(JSON.parse(xhr.response));
var res = JSON.parse(xhr.response);
if(res.success){
window.location.href = './获取城市.html';
}
}
}
}
ajax的封装
// 不同的部分
// 1.请求地址 url
// 2.请求方式 method
// 3.是否异步 async
// 4.发送的数据 参数 data
// 5.成功后执行的函数 success
// 6.失败后执行的函数 fail
function ajax(url, method, async, data, success, fail) {
// 01.创建异步请求对象 XMLHttpRequest
var xhr;
// 考虑到浏览器的兼容
if (window.XMLHttpRequest) {
// 所有现代浏览器(IE7+,FireFox,Chrome,Safari,Opera)
xhr = new XMLHttpRequest();
} else {
// IE5 IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求行 open(method,url,async)
if (method.toLowerCase() === "get") {
xhr.open("get", url + "?" + data, async);
// get:数据在URL后面用?拼接 不传参数
xhr.send();
} else if (method.toLowerCase() === "post") {
xhr.open("post", url, async);
// post:会有参数 要发送的数据(以字符串的形式)写在send()中
// 设置请求头 setRequestHeader()
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
} else {
console.error("错误", "请求方式错误")
}
// onreadystatechange 当状态发生变化时触发
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var res = JSON.parse(xhr.response); //将获取到的数据转换为对象
success(res)
} else {
fail(xhr.status, xhr.statusText)
}
}
}
}
总结
ajax涉及到前后端的一个交互了,刚开始听的时候,有种云里雾里的感觉,听着听着就要睡着了,在刚开始练习的时候,基本也是什么都不会,但是做了两次练习之后就慢慢地有一些体会了。
ajax主要的就是找到一个接口,然后根据判断从这个接口里想办法,获取到自己需要的值,然后再进行处理。刚开始时,自己的困惑是出在了,怎么去找到接口,并从接口里获取内容,那现在的问题转变为了,怎么处理获取的数据,虽然问题依然存在,但是我认为还是有些进步的。
最后再来讲一讲今天的作业:模拟从个人中心,点击登录按钮,进入登录页面,登录之后再进入个人中心,并且让自己的姓名、电话出现在个人中心里,接着再点击设置按钮,能进入设置页面,在设置页面完成退出登录的 *** 作。
对三个页面的流程做一个简单的介绍:
个人中心
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>个人中心</title>
<style>
.content{
width: 400px;
height: 600px;
border: 2px solid ;
margin: 0 auto;
text-align: center;
}
button{
width: 200px;
height: 40px;
line-height: 40px;
text-align: center;
margin-top: 50px;
cursor: pointer;
}
p{
margin-top: 20px;
}
#set{
display: none;
}
.center{
margin: 20px auto;
display: block !important;
}
</style>
</head>
<body>
<!-- 版心 -->
<div class="content">
<p><i>用户名:</i><span id="useName"></span></p>
<p><i>手机号:</i><span id="phone"></span></p>
<button id="login">点击登录</button>
<button id="set">设置</button>
</div>
</body>
<script>
// 获取元素
var oLogin = document.getElementById('login');
var oSet = document.getElementById('set');
var oUse = document.getElementById('useName');
var oPhone = document.getElementById('phone');
// 1.登录按钮
oLogin.onclick = function(){
console.log(11);
window.location.href = './login.html'; // 点击跳转到登录页面
}
// 2.当缓存中存在用户姓名时,就调用出来
if(window.localStorage.name){
oUse.innerText = window.localStorage.name;
// 当用户姓名里有值的时候,登录按钮消失,设置按钮出现
oLogin.style.display = 'none'; // 登录
oSet.className= 'center'; // 设置
}
// 3.当缓存中有电话号码时,调用出来
if(window.localStorage.phone){
var arr = window.localStorage.phone.split(''); // 将电话号码转换为数组
arr.splice(3,4,'*','*','*','*'); // 索引从3号开始截取,截取4位,替换为*
var str = arr.join(''); // 将数组转换为字符串
oPhone.innerText = str; // 将字符串输出
}
// 设置按钮
oSet.onclick = function(){
window.location.href = 'set.html'; // 点击设置按钮,跳转到设置页面
}
</script>
</html>
登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页面</title>
<style>
.content {
width: 400px;
height: 600px;
border: 2px solid;
margin: 0 auto;
text-align: center;
}
button {
width: 200px;
height: 40px;
line-height: 40px;
text-align: center;
margin-top: 50px;
cursor: pointer;
}
input {
width: 160px;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="content">
登录名:<input type="text" id="useName"><br>
密码:<input type="password" id="psw"><br>
<button>点击登录</button>
</div>
</body>
<!-- 引用封装afax的js文件 -->
<script src="./封装ajax.js"></script>
<script>
// 获取元素
var oUse = document.getElementById('useName');
var oPsw = document.getElementById('psw');
var oBtn = document.getElementsByTagName('button')[0];
// 绑定点击事件
oBtn.onclick = function () {
// 获取value值
var oUseText = oUse.value; // 点击时获取用户输入的信息
var oPswText = oPsw.value;
// 调用封装好的函数
ajax('http://146.56.207.108:3011/Handler/UserHandler?action=login', 'post', true, `userName=${oUseText}&password=${oPswText}`, function (res) {
console.log(res);
if (res.success) { // 如果success里面有值,那么就进行以下的代码
window.localStorage.setItem('name', res.data.userName); // 将姓名存到缓存中
window.localStorage.setItem('phone', res.data.phone); // 存入电话号
window.location.href = 'personal.html'; // 跳转到个人中心
} else {
alert(res.err); // d窗报错
}
}, function (status, statusText) {
console.log(status, statusText);
})
}
</script>
</html>
设置页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>设置页面</title>
<style>
.content {
width: 400px;
height: 600px;
border: 2px solid;
margin: 0 auto;
text-align: center;
}
button {
width: 200px;
height: 40px;
line-height: 40px;
text-align: center;
margin-top: 50px;
cursor: pointer;
}
p {
margin-top: 20px;
}
</style>
</head>
<body>
<!-- 版心 -->
<div class="content">
<p>手机号:<span id="phone"></span></p>
<button>退出登录</button>
<button>返回</button>
</div>
</body>
<script>
// 获取元素
var oPhone = document.getElementById('phone');
var oBtn = document.getElementsByTagName('button');
if (window.localStorage.phone) { // 当缓存中存在电话号码时,执行以下代码
oPhone.innerText = window.localStorage.phone;
}
// 退出登录
oBtn[0].onclick = function () {
if (oPhone.innerText) { // 判断是否有电话号码,有电话号码就可以点击退出登录
var sure = window.confirm('确定退出页面?');
if (sure) {
window.localStorage.clear(); // 点击按钮,直接清除缓存
window.location.href = 'personal.html'; // 跳转到个人中心页面
}
}else{
alert('沙雕,你还没有登录')
}
}
// 返回
oBtn[1].onclick = function(){
window.history.back();
}
</script>
</html>
ajax封装js文件
function ajax(url, method, async, data, success, fail) {
// 01.创建异步请求对象 XMLHttpRequest
var xhr;
// 考虑到浏览器的兼容
if (window.XMLHttpRequest) {
// 所有现代浏览器(IE7+,FireFox,Chrome,Safari,Opera)
xhr = new XMLHttpRequest();
} else {
// IE5 IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2.设置请求行 open(method,url,async)
if (method.toLowerCase() === "get") {
xhr.open("get", url + "?" + data, async);
// get:数据在URL后面用?拼接 不传参数
xhr.send();
} else if (method.toLowerCase() === "post") {
xhr.open("post", url, async);
// post:会有参数 要发送的数据(以字符串的形式)写在send()中
// 设置请求头 setRequestHeader()
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
} else {
console.error("错误", "请求方式错误")
}
// onreadystatechange 当状态发生变化时触发
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var res = JSON.parse(xhr.response); //将获取到的数据转换为对象
success(res)
} else {
fail(xhr.status, xhr.statusText)
}
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)