前端向后端做网络请求
如下代码:
1.创建可以做网络请求的对象
let xhr=new XMLHttpRequest()||new ActiveXObject()
2.配置连接信息
第二个参数为请求的网址
xhr.open("GET",`http://192.168.1.6:8888/ajax1?name=karen&count=20`,true)
这里会请求ajax1
3.发起网络请求
xhr.send()
4.监听网络数据
xur.onreadystatechange=function(){}
xhr.readyState==4表示网络请求成功 xhr.statue=200表示业务请求成功 xhr.statue=404表示业务请求失败
xhr.responseText表示后端返回的数据
JSON.parse()转对象
function load1(){
console.log(666);
// AJAX技术
// window.XMLHttpRequest
// 1.创建ajax对象
let xhr=new XMLHttpRequest()||new ActiveXObject()//创建的这个对象可以做网络请求
// 2. 配置联接信息
xhr.open("GET",`http://192.168.1.6:8888/ajax1?name=karen&count=20`,true)
// 3.发起网络请求
xhr.send()
// 4.监听网络数据
xhr.onreadystatechange=function(){
console.log(66666);
console.log(xhr.readyState);//xhr.readtState一直在变化1234 等于4表示后端已经返回了数据
if(xhr.readyState==4&&xhr.status==200){//status=200表示网络请求成功
console.log(xhr.responseText,11);//打印后端发送的数据
}else if(xhr.readyState==4&&xhr.status==404){
console.log(xhr.responseText,"网络请求成功业务失败");
var obj=JSON.parse(xhr.responseText)//转对象
console.log(obj);
}
}
}