XMLHttpRequest : 请求服务器上的数据资源
//1创建
var xhr = new XMLHttpRequest();
//2、调用 open 函数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
// 3、调用send函数
xhr.send();
// 4、监听 onreadystatechange事件
xhr.onreadystatechange = function() {
// readyState xhr的请求状态 status 是xhr的服务器响应状态
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
// readyState xhr的请求状态
// 0 创建未调用
// 1 open() 方法已调用
// 2 send() 方法已调用 响应该已被 接收
// 3 数据 接收中
// 4 done ajax请求完成 或失败
$.get('http://www.liulongbin.top:3006/api/getbooks', {
id: 1,
bookname: '西游记'
}, function(res) {
console.log(res);
})
$.ajax({
method: 'GET',
url: 'http://www.liulongbin.top:3006/api/getbooks',
data: {
id: 1,
bookname: '西游记'
},
success: function(res) {
console.log(res);
}
})
// URL编码与解码:使用英文字符 去表示 非英文字符
var str = '工作'
var str2 = encodeURI(str)
var str3 = decodeURI(str2)
console.log(str2);
console.log(str3);
// 使用xhr发起post请求
var xhrP = new XMLHttpRequest()
//2、调用 open 函数
xhrP.open('post', 'http://www.liulongbin.top:3006/api/addbook');
// 3、调用send函数
xhrP.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhrP.send('bookname=花游记&author=吴吴恩&publisher=长少图书出')
// 4、监听 onreadystatechange事件
xhrP.onreadystatechange = function() {
// readyState xhr的请求状态 status 是xhr的服务器响应状态
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhrP.responseText);
}
};
数据交换格式
-
xml -传输和存储数据 数据载体 标记语言
缺点: 解析麻烦 格式臃肿 无关代码多, 传输慢 -
json-字符串 轻量级文本数据交换格式
更小 快,易解析 现主流数据交换格式
// JSON和js对像互转
// JSON转为js对像 -反序列化
var obj = JSON.parse('{"a":"hello", "b": " lo", "c": "味道"}')
console.log(obj);
// js对像转为JSON -序列化
var json = JSON.stringify({
a: '要做什么',
b: '最悲惨',
c: '真的自己'
})
console.log(json);
// JSON应用
var xhrG = new XMLHttpRequest()
xhrG.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
xhrG.send();
xhrG.onreadystatechange = function() {
if (xhrG.readyState === 4 && xhrG.status === 200) {
console.log(xhrG.responseText);
// 转换
var result = JSON.parse(xhrG.responseText);
console.log(result);
}
};