创建XMLHttpRequest对象
XMLHttpRequest主要用于和后台服务器交换数据,就可以在不加载整个网页的前提下对网页进行局部更新
let xmlHttpRequest = new XMLHttpRequest();
几个相关api
method表示请求的类型,可以为GET或者POST;async为true表示异步请求,false表示同步请求,默认为异步请求
用来规定请求的类型,以及是否异步处理
open(method, url, async)
data为请求的数据,只可以用于POST请求
用来将请求发送到服务器
send(data)
每当 readyState 属性改变时,就会回调该函数
onreadystatechange
保存XMLHttpRequest的状态,在请求期间会变化
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
readyState
请求的状态码
status
开启http请求
// open必须在调用的最前面
// 如果是"/selected",实际的url是http://www.xxx.com/selected
// 如果是"selected",实际的url是http://www.xxx.com/xxx/xxx/selected
xmlHttpRequest.open("POST", "/selected", true);
// 发送urlencoded数据
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send('name=steven&&age=94'); // 如果是post请求必须调用send函数
// 发送json格式数据
xmlHttpRequest.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xmlHttpRequest.send('{"name": "steven", "age": 14}');
获得响应内容
xmlHttpRequest.onreadystatechange = function (ev) {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
}
}
json字符串和对象的相互转换
//字符串转json对象
let json_obj =JSON.parse('{"name":"steven","age":19}')
//json对象转字符串
let json_obj_str = JSON.stringify(json_obj);
一个例子
$.ajax({
url: "http://127.0.0.1:5000/",
type: 'GET',
success: function(data) {
console.log(data)
},
error: function(err) {
console.error(err)
}
})