今天上午复习完毕了 ajax 接下来我们以笔记的形式来进行总结
//创建Ajax对象
var xhr = new XMLHttpRequest();
//告诉ajax的请求地址 以及请求方式
xhr.open("get", "http://localhost:3000/index");
// 发送请求
xhr.send();
// 获取服务端给客户端的响应数据
xhr.onload = function () {
console.log(xhr.responseText);
}
我们在请求返回json数据的时候 需要把数据幻化为JSON.parse
//创建Ajax对象
var xhr = new XMLHttpRequest();
//告诉ajax的请求地址 以及请求方式
xhr.open("get", "http://localhost:3000/responseData");
// 发送请求
xhr.send();
// 获取服务端给客户端的响应数据
xhr.onload = function () {
console.log(xhr.responseText);
var res = JSON.parse(xhr.responseText);
console.log(res);
console.log(res[0].name);
s1.innerText =res[0].name;
s2.innerText =res[0].age;
s3.innerText =res[0].sex;
}
xhr.open("post", "http://localhost:3000/json" );
// 设置请求 配置等等
xhr.setRequestHeader("Content-Type","application/json");
京公网安备 11010502036488号