(syntax)ajax
2022-09-01 00:00:00

ajax

创建XHR(XMLHttpRequest) ==> 请求 => 响应 => 发送

  • 创建XHR
    • new XMLHttpRequest
    • new ActiveXObject(“Microsoft.XMLHTTP”)
  • XHR请求 open(method,URL,true)
  • onreadyStateChange事件
    • readyState = 4
    • status = 200
  • XHR响应 responseText/XML
    • responseText 获得字符串形式的响应数据
    • responseXML 获得 XML 形式的响应数据
  • XHR发送 send()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var xhr = ''

if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new AcitveXObject("Microsoft.XMLHTTP");
}

// xlhttp.setRequestHeader("Content-type","application/x-www-form-unclencoded");
// 添加 HTTP 头向请求添加 HTTP 头。*header*: 规定头的名称*value*: 规定头的值
xhr.open("GET","/api",true)
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
console.log(xhr.responseText)
}
}
}
xhr.send()
1
2
3
4
5
6
7
8
9
$.ajax({
url: 'test.php', // 请求地址
jsonp: 'jsonpCallback', // 采用jsonp请求,且回调函数名为"jsonpCallbak",可以设置为合法的字符串
data: {'b': '异步请求'}, // 传输数据
success:function(res){ // 请求成功的回调函数
console.log(res);
},
error: function(error) {} // 请求失败的回调函数
});

fetch

json

  • stringify 字符串化 parse 解析
  • JSON.parse('JS字符串') 解析JS字符串(单引号)JSON.parse('{"name":"zs"}')
  • JSON.stringify({}) 字符串化 JSON.stringify({name:"zs"})
上一页
2022-09-01 00:00:00
下一页