Ajax响应数据格式
2019-05-21 本文已影响0人
CNLISIYIII
(一)同步和异步
xhr.open()
方法第三个参数要求传入的是一个 布尔值
,其作用就是设置此次请求是否采用异步方式执行,默认为 true
异步,修改为false
为同步。
异步代码举栗:
console.log('before ajax')
var xhr = new XMLHttpRequest()
// 默认第三个参数为 true 意味着采用异步方式执行
xhr.open('GET', '/time', true)
xhr.send(null)
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
// 这里的代码最后执行
console.log('request done')
}
}
console.log('after ajax')
//输出结果:
//before ajax
//after ajax
//request done
如果采用同步方式执行,则代码会卡死在 xhr.send() 这一步:
同步代码举栗:
console.log('before ajax')
var xhr = new XMLHttpRequest()
// 同步方式
xhr.open('GET', '/time', false)
// // 同步方式 执行需要 先注册事件再调用 send,否则 readystatechange 无法触发
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
// 会按代码执行顺序执行这行代码
console.log('request done')
}
}
xhr.send(null)
// 因为 send 方法执行完成 响应已经下载完成
console.log(xhr.responseText)
console.log('after ajax')
//输出结果:
//before ajax
//request done
//1558437144572
//after ajax
(二)XMLHttpRequest API
1.属性
-
readyState
xhr的状态 4 响应体(服务器返回的数据)接收完毕 -
status
获取状态码 -
responseText
获取响应体,文本格式 -
responseXML
获取响应体,xml格式 -
onreadystatechange
事件,当xhr.readyState属性发生改变触发 -
onload
事件,响应接收完毕
2.方法
-
open(method, url, async)
设置请求的方式,请求的路径, 同步/异步 -
send(requsetBody)
发送请求(体) -
setRequestHeader(key, value)
设置请求头 -
getResponseHeader(key)
获取响应头
(三)响应数据格式
1.JSON
JSON的本质是字符串。
- JSON 中属性名称必须用双引号包裹
- JSON 中表述字符串(值)必须使用双引号
- JSON 中不能有单行或多行注释
- JSON 没有
undefined
这个值 - 一个完整的JSON,不能有其他内容掺杂
数据类型:null,number,boolean,string,object,array
2.数据转换
JSON转JS:JS = JSON.parse(JSON)
JS转JSON:JSON = JSON.stringify(JS);
代码举栗:
// JS数据和JSON数据相互转换
// 先定义一些JS数据
var js_b = true;
var js_o = {name: 'zs', age: 20, sex: 'M'};
var js_a = ['red', 'green', 'blue'];
console.log(js_b);
console.log(js_o);
console.log(js_a);
// 1. JS数据转换成JSON格式
var json_b = JSON.stringify(js_b);
var json_o = JSON.stringify(js_o);
var json_a = JSON.stringify(js_a);
console.log(json_b);
console.log(json_o);
console.log(json_a);
// 2. 把JSON数据转换成JS数据
console.log(JSON.parse(json_b));
console.log(JSON.parse(json_o));
console.log(JSON.parse(json_a));
(四)模版引擎
数据结构简单的时候可以使用模版引擎。实际上就是一个API。
- artTemplate:https://aui.github.io/art-template/
使用步骤:
- 准备一个存放数据的盒子(不是必须的,使用body也可以)
- 引入template-web.js文件
- 定义模板(具体语法可以去官网查看),一定要指定script的id和type属性
- 调用template函数,为模板分配数据,template函数有两个参数一个返回值
1)参数1:模板的id
2)参数2:分配的数据,必须是一个JS对象的形式
3)一个返回值:是数据和模板标签组合好的结果 - 将 “拼接” 好的结果放到准备好的盒子中(不是必须的,console出来也可以看结果)
定义模板时的script标签一定好指定id
和type
tempalte函数语法:var html = template(模板id, Object);
代码举栗:
<!-- 1. 定义一个模板,要指定script的id和type属性 -->
<script id="moban" type="text/html">
<h1>{{title}}</h1>
<ul>
<li>
<p>{{chenghu}}</p>
<p>{{liuyan}}</p>
</li>
</ul>
</script>
<script src="./assets/template-web.js"></script>
<script>
// 调用template函数
// 两个参数,一个返回值
// 参数1:模板的id
// 参数2:要显示的数据,必须是JS对象的形式
// 返回值:数据和模板拼接好的结果
var html = template('moban', {
title: '留言板123',
chenghu: '张三',
liuyan: 'hahahahahaha哈哈哈'
});
console.log(html);
document.body.innerHTML = html;
</script>
留言板案例
html代码:
<body>
<div class="area">
<img src="img/tip.png">
<input type="text" id="userName" placeholder="输入用户名...">
<span id="msg"> </span>
<textarea maxlength="200" placeholder="说点儿什么叭。。。"></textarea>
<p>
<span>字数:</span>
<span id="words">0</span>/
<span>200</span>
<button class="sub">发布</button>
</p>
</div>
<ul>
<!--
<li>
<div class='topDiv'>
<img src="" alt="">
<span>用户名</span>
<p>时间</p>
</div>
<div class='bottomDiv'>内容</div>
</li>
-->
</ul>
<div class="top">⬆️<br>回到顶部</div>
<script src="lib/jquery-1.12.4.js"></script>
<script src="js/index.js"></script>
<script id="model" type="text/html">
<li>
<div class='topDiv'>
<img src="img/03.png">
<span>{{name}}</span>
<p>发布于:{{time}}</p>
</div>
<div class='bottomDiv'>{{content}}</div>
</li>
</script>
<script src='js/template-web.js'></script>
</body>
index.js代码:
var userText = document.querySelector('textarea');
var name;
var content;
var isOk = 0;
userText.oninput = function () {
$('#words').text(this.value.length);
content = userText.value;
}
document.getElementById('userName').onblur = function () {
var xhr = new XMLHttpRequest();
name = this.value;
xhr.open('POST', '/checkUser');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('username=' + name);
xhr.onload = function () {
var result = this.responseText;
// console.log(result);
if (result === 'true') {
document.getElementById('msg').innerText = '啊呀这个名字被用过啦!';
$('#msg').css('color', 'red');
isOk = 0;
}
else if (result === 'false') {
document.getElementById('msg').innerText = 'congratulations! 这个名字可以用!';
$('#msg').css('color', 'green');
isOk = 1;
}
if (name === '') {
document.getElementById('msg').innerText = '让我知道我喜欢的你叫什么名字好嘛~';
$('#msg').css('color', 'gold');
}
}
}
function resetAll() {
document.getElementById('userName').value = '';
userText.value = '';
$('#words').text('0');
document.getElementById('msg').innerText = ' ';
name = '';
content = '';
}
// var oldLi = $('ul').children[0];
// var newLi = $('ul').children('li');
$('.sub').click(function () {
var xhrClick = new XMLHttpRequest();
var lisHtml = template('model', {
name: name,
time: new Date().toLocaleString(),
content: content,
});
if (name == '' || content == '') {
resetAll();
alert('难道你就这么不愿意留言说爱我吗!');
}
else {
if (isOk) {
xhrClick.open('POST', '/addMsg');
xhrClick.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhrClick.send('name' + name + '&content' + content);
xhrClick.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.responseText) {
$('ul').append(lisHtml);
// $('ul').insertBefore(newLi,oldLi);
}
}
}
}
else {
alert('换个名字试试叭!');
}
}
resetAll();
})
var liTop = $('ul').offset().top;
console.log(liTop);
$(window).scroll(function() {
if($(window).scrollTop() >= liTop) {
$('.top').css('display','block');
}
else {
$('.top').css('display','none');
}
})
$('.top').click(function() {
$('html,body').animate({scrollTop:0},'linear');
})