一、创建和封装第一个AjAX
1、ajax是一个框架技术。
定义
//分为五步
//需要在服务器中打开文件
1、创建异步对象
var xhttp = new XMLHttpRequest();
2、设置请求方法 和请求地址
xhtttp.open();
3、发送请求
xhttp.send();
4、监听状态变化
xhttp.onreadystatechange = function(){
}
5、处理返回结果
xhttp.readyState xhttp状态
xhttp.satus http状态码
语法格式
//需要在js代码中对ajax进行编辑
<script>
// 1、创建异步对象
var xhttp = new XMLHttpRequest();
// 2、设置请求方式和请求地址
// open() 中一共有三个参数
// 1、 请求方式: GET POST
// 2、 请求的地址
// 3、同步 false 还是异步 true
xhttp.open('get', 'one.php', true);
// 3、发送请求
// send();方法2、封装ajax
封装的ajax代码
xhttp.send();
// 4、监听状态变化
xhttp.onreadystatechange = function() {
// 5、处理返回结果
// console.log(xhttp.readyState);
// xhttp.readyState --- xhttp的状态
// 0~4 只用4是处理成功
if (xhttp.readyState == 4) {
// xhttp.state保存到了http状态码
// 200 ~500多 200~300之间为符合 或者是 304页面缓存
if (xhttp.status >= 200 && xhttp.status <= 300 || xhttp.status
== 304) {
console.log('有结果返回');
console.log(xhttp.responseText);
}
}
}
</script>
2、封装ajax
封装的ajax代码
//书写函数将对象转化为我们需要的字符串
function obj(data) {
//1、放入一个数组中,声明一个空数组。
var arr = [];
//将数组拼接成我们需要的字符串
//将对象中的数据进行遍历,然后拼接到数组中
for (var key in data) {
//通过push方法将对象中的数据放置到数组中,
arr.push(key + '=' + data[key]);
}
//将目标数组拼接成字符串 join方法
var str = arr.join('&');
// console.log(str);
return str;
}
//函数有形参,有实参,
function ajaxGet(url, data, success, error) {
//获取按钮
// 1、创建异步对象
var xhttp = new XMLHttpRequest();
// 2、设置请求方式和请求地址
//name=zhangsan&zex=man"
//我们创建了一个obj的方法用来获取传入的数据,将数据转化为字符串。
var str = obj(data);
xhttp.open('get', url + '?' + str, true);
// 3、发送请求;
xhttp.send();
// 4、监听状态变化
xhttp.onreadystatechange = function() {
// 5、处理返回过程
if (xhttp.readyState == 4) {
//http响应码 正确的响应码的范围是200~300之间,304--页面缓存
if (xhttp.status == 304 || xhttp.status >= 200 && xhttp.status <=
300) {
// console.log(xhttp.responseText); success(xhttp); } else { // console.log('响应失败'); error(xhttp); } } } }
3、常见的xml和json
定义:
XML
XML
指可扩展标记语言(
e
X
tensible
M