Ajax的使用
GET方法
//1创建按一个变量
var xhr=null;
//2 判断浏览器的环境
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr=new ActiveXObject("Mircosoft.XMLHttp")
}else{
throw new Error("您的浏览器不支持AJAX 请升级浏览器")
}
//5 监听请求
xhr.onreadystatechange=function(){
//当xhr对象的readyState属性发生了改变,这个时间就会触发
//readyState;
//0===>xhr对象已经创建,但是还没有进行初始化操作
//1===>xhr对象已经调用了open()
//2===>xhr已经发出了ajax请求
//3===>已经接受道部分数据
//4===>数据已经全部返回
if(xhr.readyState!==4){
return;
}
if(xhr.status>=200 && xhr.status <=300){
//数据存在xhr.responseText的属性中(String)
document.querySelector("h1").innerHTML=xhr.responseText
}else{
console.error("请求失败")
}
}
//3打开这个对象
xhr.open("get",'./test.txt',true);
//4 发送请求
xhr.send();
POST方法
//1创建按一个变量
var xhr=null;
//2 判断浏览器的环境
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr=new ActiveXObject("Mircosoft.XMLHttp")
}else{
throw new Error("您的浏览器不支持AJAX 请升级浏览器")
}
//6 监听数据返回
xhr.onreadystatechange=function(){
if(xhr.readystate!==4){
return;
}
if(xhr.status>=200 && xhr.status<=300){
var resp=JSON.parse(xhr.responseText);
if(resp.result){
alert("登录成功")
}else(
console.error("登录失败")
)
}
}
//3 设置这个对象
xhr.open("post",'./login',true);
//4 设置请求头,指明body中的数据是那种格式
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded,charset=utf-8");
//5发送数据
xhr.send("us=wanlaowu&ps=123456")
通过Promise这个构造函数来创建一个对象
*Promise对象有三个状态 pending,resolve,reject状态
Promise构造函数,有一个参数,这个参数是一个回调 这个回调,接受两个参数 这两个参数都能改变
Promise对象的状态,第一个参数,可以将状态从pending==>resolve ,而第二个参数可以将状态从pending=>reject*
基本用法:
var promise=new Promise(function(resolve,reject){
if(/*成功*/){
resolve(num);//输出的值
}else{
reject(num);//输出的值
}
})
验证Promise
var promise =new Promise(function(resolve,reject){
setTimeout(function(){
var num=Math.floor(Math.random()*100);
if(num%2==0){
resolve(num);
}else{
reject(num);
}
},3000)
})
promise.then(function(num){
console.log("resolve"+" "+num)
}).catch(function(num){
console.log("reject"+" "+num)
})
回调地狱的问题
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
var article="";
$.get('./p1.txt',function(p1){
article+=p1+"<br/>"
$.get('./p1.txt',function(p2){
article+=p2+"<br/>"
$.get('./p1.txt',function(p3){
article+=p3+"<br/>"
$.get('./p1.txt',function(p4){
article+=p4+"<br/>";
$("p").html(article)
})
</script>
使用Promise解决回调地狱的问题
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
function getPara1(){
return new Promise((resolve, reject)=>{
$.get("./p1.txt",(p1)=>{
resolve(p1);
})
})
}
function getPara2(){
return new Promise((resolve, reject)=>{
$.get("./p2.txt",(p1)=>{
resolve(p1);
})
})
}
function getPara3(){
return new Promise((resolve, reject)=>{
$.get("./p3.txt",(p1)=>{
resolve(p1);
})
})
}
function getPara4(){
return new Promise((resolve, reject)=>{
$.get("./p4 .txt",(p1)=>{
resolve(p1);
})
})
}
var article="";
getPara1().then((p1)=>{
article+=p1+"<br>";
return getPara2();
}).then((p2)=>{
article+=p2+"<br>";
return getPara3();
}).then((p3)=>{
article+=p3+"<br>"
return getPara4((p4)=>{
article+=p3+"<br>";
$("p").html(article)
});
})
JSONP解决跨域问题
JSONP: json + Padding
JSONP是一种跨域请求数据的方式,json是一种数据格式
原理:
我们可以利用script标签无视同源策略的特点,将src属性指向目标服务器上的接口,我们发现,确实可以将数据请求回来,但是,报了一个错误是语法错误 我们要将这个语法错误, 变成代码执行时候的错误,必须到目标服务器中修改源码,还要提前定义要执行的函数 函数中的参数就是请求回来的数据
封装JSONP函数
前端
//封装JSONP
/*
* @url 本次请求的路径
* @data 携带的数据(对象)
* @callback 成功时执行的函数
*/
function jsonp(url,data,callback){
//处理data 转为query字符串
var str="";
//遍历data
for(var i in data){
str+="&"+i+"="+data[i]
}
//截取str
str=str.slice(1);
//创建一个Script标签
var script=document.createElement("script");
script.src=url+"?"+str;
console.log(str)
//提前把callback方法定义在全局中
window[data.callback]=callback;
//script标签必须上树之后才能发送请求
document.body.appendChild(script);
//当请求完毕之后 移除script
script.onload=function(){
//移除script 标签
script.parentNode.removeChild(script)
//移除添加的方法
// delete window[data.callback];
}
}
function hello(res){
console.log(res)
}
//使用
jsonp("http://localhost:3000/getMsg",{us:"wanglaowu",callback:"hello"},function(res){
console.log(111,res)
})
后端处理JSONP请求
//引入express()
const express=require("express");
//创建服务器
const app=express();
//处理jsonp请求
app.get('/getMsg',(req,res)=>{
let {us,callback}=req.query;
// console.log(us,callback,req.query)
let _data={
err:0,
data:"请求成功"
}
// 设置返回类型为javascript
// res.type("text/javascript");
res.send(callback+"("+JSON.stringify(_data)+")")
})
//监听服务器
app.listen(3000,()=>{
console.log("app listen at 3000 && server start")
})
Cors 跨域资源共享(所有浏览器都支持该功能,IE浏览器不能低于IE10) 后端解决跨域问题
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
JSONP模拟百度搜索发送
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text">
<ul></ul>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
//处理返回的数据并渲染
function getData(data){
var script=document.querySelector("#jsonp");
script.parentNode.removeChild(script);
$("ul").html('');
for(var i=0;i<data.s.length;i++){
$("<li>"+data.s[i]+"</li>").appendTo("ul");
}
}
//JSONP
function getList(wd){
var script=document.createElement("script");
script.id="jsonp";
script.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?cb=getData&wd="+wd;
document.body.appendChild(script);
}
//获取input输入的字并调用JSONP的方法
$("input").keyup(function(){
var wd=$(this).val();
getList(wd)
})
</script>
</body>
</html>