1、同步异步
- 异步代码总是在同步代码之后执行
2、ajax特点
3、get、post请求
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3mgr2Cud-1587039388077)(file:///C:\Users\ZHY\AppData\Roaming\Tencent\Users\2594851761\QQ\WinTemp\RichOle\NGQ7UYC{%7@HHQ4D0@A6_JQ.png)]
3.1、get请求
-
get.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <button onclick="sendMsg()">发送请求</button> <div></div> <script> function sendMsg(){ //1. 创建一个XMLHttpRequest对象 var xhr = new XMLHttpRequest() //2.调用open方法打开连接 //open方法有三个 // 1、请求的method // 2、请求的url // 3、是否异步,默认异步 xhr.open('get','./data.php?id=1') // 3、发送请求 xhr.send(); // 4 监听状态的改变 xhr.onreadystatechange=function(){ //判断状态值,0-4 五种状态, 4代表最终的完成 if(xhr.readyState===4){ //判断状态码 if(xhr.status===200){ var resp = JSON.parse(xhr.responseText) console.log(resp) document.querySelector('div').innerHTML=` <h2>编号: ${resp.id}</h2> <h2>标题: ${resp.title}</h2> ` } } } } </script> </body> </html>
-
data,php
<?php $id=$_GET['id']; // echo 'hello ajax'; echo json_encode(array( 'id'=>$id, 'title'=>'hello ajax' )) ?>
3.2、post请求
post.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="sendMsg()">发送请求</button>
<div></div>
<script>
function sendMsg(){
var xhr = new XMLHttpRequest()
xhr.open('post','./data.php')
//设置请求头的content-type
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send('name=zhangsan&age=18')
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var resp=JSON.parse(xhr.responseText)
console.log(resp)
document.querySelector('div').innerHTML=`
<h2>姓名: ${resp.name}</h2>
<h2>年龄: ${resp.age}</h2>
<h2>余额: ${resp.money}</h2>
`
}
}
}
}
</script>
</body>
</html>
data.php
<?php
$name=$_POST['name'];
$age=$_POST['age'];
echo json_encode(array(
"name"=>$name,
"age"=>$age,
'money'=>9999
))
?>
4、ajax封装上
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="sendMsg()">发送请求</button>
<script>
function sendMsg(){
// get('./data.php',{id:2,title:'lisi'},function(resp){
// console.log(resp)
// },true)
post('./data2.php',{id:2,title:'lisi'},function(resp){
console.log(resp)
},true)
}
//封装get
// url:string,请求地址
// query object,请求携带的参数
// callback回掉函数:function 成功之后的回调
// isJson boolean, 是否需要解析json
function get(url,query,callback,isJson){
// 如果有参数,先把参数拼接在url后面
if (query) {
url += '?'
for (var key in query) {
url += `${key}=${query[key]}&`
}
// 取出最后多余的 &
url = url.slice(0, -1)
}
var xhr = new XMLHttpRequest;
xhr.open('get',url)
xhr.send()
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var res = isJson?JSON.parse(xhr.responseText):xhr.responseText
callback(res)
}
}
}
}
function post(url,query,callback,isJson){
// 如果有参数,先把参数拼接
str=''
if (query) {
for (var key in query) {
str += `${key}=${query[key]}&`
}
// 取出最后多余的 &
str = str.slice(0, -1)
}
var xhr = new XMLHttpRequest;
xhr.open('post',url)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(str)
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var res = isJson?JSON.parse(xhr.responseText):xhr.responseText
callback(res)
}
}
}
}
</script>
</body>
</html>
data.php
<?php
$id=$_GET['id'];
$title=$_GET['title'];
echo json_encode(array(
'id'=>$id,
'title'=>$title,
'age'=>19
))
// echo 'hello get';
?>
data2.php
<?php $id=$_POST['id']; $title=$_POST['title']; echo json_encode(array( 'id'=>$id, 'title'=>$title, 'age'=>19 )) // echo 'hello get'; ?>5、ajax封装下
util.js
var util={
get:function(url,query,callback,isJson){
if (query) {
url += '?'
for (var key in query) {
url += `${key}=${query[key]}&`
}
// 取出最后多余的 &
url = url.slice(0, -1)
}
var xhr = new XMLHttpRequest;
xhr.open('get',url)
xhr.send()
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var res = isJson?JSON.parse(xhr.responseText):xhr.responseText
callback(res)
}
}
}
},
post:function(url,query,callback,isJson){
str=''
if (query) {
for (var key in query) {
str += `${key}=${query[key]}&`
}
// 取出最后多余的 &
str = str.slice(0, -1)
}
var xhr = new XMLHttpRequest;
xhr.open('post',url)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(str)
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var res = isJson?JSON.parse(xhr.responseText):xhr.responseText
callback(res)
}
}
}
},
// params:object:{method,url,query,callback,isJson}
ajax:function(params){
var xhr = new XMLHttpRequest()
if(params.method.toLowerCase()==='get'){
if(params.query){
params.url += '?'
for (var key in params.query) {
params.url += `${key}=${params.query[key]}&`
}
// 取出最后多余的 &
params.url = params.url.slice(0, -1)
}
xhr.open('get',params.url)
xhr.send()
}else{
// post
str=''
if (params.query) {
for (var key in params.query) {
str += `${key}=${params.query[key]}&`
}
// 取出最后多余的 &
str = str.slice(0, -1)
}
xhr.open('post',params.url)
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
xhr.send(str)
}
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
var res = params.isJson?JSON.parse(xhr.responseText):xhr.responseText
params.callback(res)
}
}
}
}
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./util.js"></script>
<title>Document</title>
</head>
<body>
<button onclick="sendMsg()">发送请求</button>
<script>
function sendMsg(){
util.ajax({
method:'get',
url:"./data.php",
query:{id:2,title:'lisi'},
callback:function(resp){
console.log(resp)
},
isJson:true
})
}
</script>
</body>
</html>
6、Ajax实战
接口:
列表接口:https://api.apiopen.top/getJoke
详情接口:https://api.apiopen.top/getSingleJoke?sid=段子id
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./util.js"></script>
<title>段子详情</title>
</head>
<body>
<ul id="wrap">
</ul>
<!-- 列表接口:https://api.apiopen.top/getJoke
详情接口:https://api.apiopen.top/getSingleJoke?sid=段子id -->
<script>
// 页面一开始查询段子列表
util.get('https://api.apiopen.top/getJoke',null,function(resp){
console.log(resp)
var html=''
// 拼接li字符串到ul里面
resp.result.forEach(function(item){
html += `
<li>
<h3>${item.text}</h3>
<button data-id="${item.sid}">查看详情</button>
</li>
`
})
document.querySelector('#wrap').innerHTML=html
},true)
// 事件委托 给button添加事件
document.querySelector('#wrap').onclick=function(e){
var target=e.target
if(target.tagName==='BUTTON'){
// 从按钮的自定义属性上取到sid
var sid = target.getAttribute('data-id')
util.get('https://api.apiopen.top/getSingleJoke',{sid:sid},function(resp){
console.log(resp)
var name = resp.result.name
// 找到父级li,插入作者信息
var b = document.createElement('b')
b.innerHTML=name
target.parentNode.appendChild(b)
},true)
}
}
</script>
</body>
</html>
7、promise
把异步代码封装成同步代码
1、封装基于promise的get请求
util.js
// 基于promise的get请求
// return new Promise
fetch: function (url, query, isJson) {
if (query) {
url += '?'
for (var key in query) {
url += `${key}=${query[key]}&`
}
url = url.slice(0, -1)
}
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest()
xhr.open('get', url)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var resp = isJson ? JSON.parse(xhr.responseText) : xhr.responseText
resolve(resp)
} else {
reject()
}
}
}
})
}
get.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./util.js"></script>
<title>Document</title>
</head>
<body>
<button onclick="sendMsg()">发送请求</button>
<script>
function sendMsg () {
// 把异步代码写成同步形式,不用传回调函数了,而是在then里处理成功
util.fetch('./data.php', { id: 3}, true).then(function (resp) {
console.log(resp)
})
}
</script>
</body>
</html>
data.php
<?php
$id=$_GET['id'];
echo json_encode(array(
'id'=>$id,
'title'=>'yuyu'
))
?>
8、同源策略
同源:协议、域名、端口号三者完全一致
9、解决跨域之cors
cross origin resource sharing 跨域资源共享
使用方式:后端设置响应头
header(‘Access-Control-Allow-Origin:*’’)//允许所有的前端跨域访问
10、解决跨域之jsonp
- src属性有开放性原则
- jsonp只能解决get请求
11、jsonp实战
模仿百度搜索
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>百度搜索</title>
</head>
<body>
<div>
<img src="https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo_top-e3b63a0b1b.png">
<input type="text" id="search">
<!-- https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=关键字&cb=回调函数名 -->
</div>
<ul id="list"></ul>
<script>
var search = document.querySelector('#search')
var list = document.querySelector('#list')
search.onkeyup=function(){
var text=this.value
var script = document.createElement('script')
script.src=` https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=${text}&cb=fn`
document.body.appendChild(script)
// 过河拆桥
document.body.removeChild(script)
}
list.onmousedownk=function(e){
var target=e.target
if(target.tagName==='LI'){
search.value=target.innerHTML
// mousedown之后会立即触发search的blur事件
list.innerHTML=''
}
}
// input失去焦点
search.onblur=function(){
list.innerHTML=''
}
function fn(resp){
console.log(resp)
var html=''
resp.s.forEach(function(word){
html += `<li>${word}</li>`
})
list.innerHTML=html
}
</script>
</body>
</html>