1.同步和异步

  1. 同步:客户端向服务器端发送请求的时候,用户不能进行其他操作<br /> 异步:客户端向服务器端发送请求的时候,用户可以进行其他操作<br /> 对资源的操作都是异步的
  1. <p id="app"></p>
  1. var app=document.getElementById("app")
  2. var url = "http://192.168.4.18:8000/";
  3. /* ajax 如何使用ajax向后台获取数据*/
  4. /*1.创建ajax核心对象*/
  5. var xhr = new XMLHttpRequest();
  6. /*2.与服务器建立连接,xhr.open(method,url,async)
  7. 请求的方式,地址,是否异步*/
  8. xhr.open("get",url,true)
  9. /*3.发送请求*/
  10. xhr.send()
  11. /*4.响应*/
  12. /*onreadystatechange 监听服务器的响应状态*/
  13. xhr.onreadystatechange = function(){
  14. /* xhr.status 服务器端响应的状态码 200 */
  15. /* xhr . readystate 服务器响应的进度 4响应已经完成*/
  16. if(xhr.readyState == 4 && xhr.status == 200){
  17. /* JSON. parse()可 以json格式的字符串,转换为json格式的数据*/
  18. var arr = JSON.parse(xhr.responseText);
  19. console.log(arr);
  20. app.innerHTML= arr.name;
  21. }
  22. }

2.ajax的使用

  1. <p id="app">
  2. </p>
  1. /*
  2. 1.什么是异步 何时使用
  3. 2.如何使用原生ajax
  4. */
  5. var app = document.getElementById("app")
  6. var url ="http://192.168.4.18:8000/"
  7. /* ajax 如何使用ajax向后台获取数据*/
  8. /* 1. 创建ajax核心对象*/
  9. var xhr = new XMLHttpRequest();
  10. /* 2.与服务器建立连接 xhr.open(method,url,async)
  11. 请求的方式,地址,是否异步
  12. */
  13. xhr.open("get",url,true)
  14. /* 3.发送请求 */
  15. xhr.send()
  16. /* 4.响应 */
  17. /* onreadystatechange 监听服务器的响应状态*/
  18. xhr.onreadystatechange = function(){
  19. /* xhr.status 服务器端响应的状态码 200 */
  20. /* xhr.readyState 服务器响应的进度 4 响应已经完成 */
  21. if(xhr.readyState == 4 && xhr.status == 200){
  22. var txt = xhr.responseText;
  23. /* JSON.parse() 可以json格式的字符串,转换为json格式的数据 */
  24. var obj = JSON.parse(txt);
  25. console.log(obj)
  26. app.innerHTML = obj.name
  27. }
  28. }

3.Ajax的封装

html文件

  1. var url = "http://192.168.4.18:8000/"
  2. ajax({
  3. url,
  4. method:"get",
  5. success:res=>{
  6. console.log(res)
  7. }
  8. })

js文件

  1. function ajax({
  2. url,
  3. method,
  4. success
  5. }) {
  6. var xhr = new XMLHttpRequest()
  7. xhr.open(method, url, true)
  8. xhr.send()
  9. xhr.onreadystatechange = function () {
  10. if (xhr.readyState == 4 && xhr.status == 200) {
  11. var res = JSON.parse(xhr.responseText);
  12. success(res);
  13. }
  14. }
  15. }

4.get和post

  1. get
  2. 1.用来请求数据
  3. 2.请求放在url地址里面的,对用户是不可见的
  4. 3.发送的信息也是有限的
  5. post
  6. 1.提交数据
  7. 2.发送数据对用户来说是不可见
  8. 3.发送数据理论上是没有限制的

5.跨域

4-1 域名

  1. chengbenchao.top //主域名
  2. www.chengbenchao.top;
  3. aaa.chengbenchao.top
  4. bbb.chengbenchao.top
  5. //www,aaa 子域名
  6. https://www.chengbenchao.top:8080/a.txt
  7. //https,http协议
  8. //a.txt 请求的资源文件
  9. 域:由协议,子域名,主域名,端口,请求的资源文件组成

4-2 跨域

  1. 跨域: 协议,子域名,主域名,端口不同时候就叫跨域
  2. 同源策略:javascript出于同源策略,不允许从一个域访问另一个域的对象。
  1. // 协议,子域名,主域名,端口 只要有一个不一样就是跨域
  2. // 以下都跨域了
  3. https://www.baidu.com
  4. http://www.baidu.com // 协议不一致
  5. https://www.baidu.com
  6. https://aaa.baidu.com // 子域名不一致
  7. https://www.baidu.com
  8. https://www.baidu.top // 主域名不一致
  9. https://www.baidu.com:8080
  10. https://www.baidu.com:80 // 端口号不一致
  11. // 未跨域
  12. https://www.baidu.com:8080/a.json
  13. https://www.baidu.com:8080/b.json

6.如何解决跨域

前端跨域
5-1 jsonp跨域

  1. Jsonp(JSON with Padding) json 的一种"使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据。
  1. /* jquery-ajax jsonp*/
  2. $.ajax({
  3. url:"http://192.168.4.18:7000/ad",
  4. method:"get",
  5. dataType:"jsonp",
  6. success:res=>{
  7. console.log(res)
  8. }
  9. })

5-2 script标签(了解)

  1. 原理: script不受同源策略的限制
  1. var script = document.createElement("script");
  2. script.src = "http://192.168.4.18:7000/ad?&callback=handleResponse";
  3. document.body.prepend(script);
  4. function handleResponse(res) {
  5. // 对response数据进行操作代码
  6. console.log(res)
  7. }

服务端跨域

  1. Access-Control-Allow-Origin','*'
  1. koa.js
  2. koa2-cors//中间
  3. const cors = require("koa2-cors");
  4. app.use(cors({
  5. origin:"*"
  6. }));
  7. //所有其他的域,都可以访问本域
  1. const koa = require("koa");
  2. const app = new koa();
  3. app.use(async ctx=>{
  4. ctx.set('Access-Control-Allow-Origin','*')
  5. ctx.body = {
  6. name:"cheng"
  7. }
  8. })
  9. app.listen(5000)

7.两个页面之间如何跳转、传值

  1. location.href =" " // 跳转到另一个页面
  2. location.search // 可设置或返回当前 URL 的查询部分(问号 ? 之后的部分)
  3. decodeURIComponent() //解码
  • music.html (跳转)

    1. <input type="text" id="input">
    2. <script>
    3. var input = document.getElementById("input")
    4. input.onkeydown = function(event){
    5. if(event.keyCode == 13){
    6. console.log(this.value);
    7. location.href = `search.html?s=${this.value}` //跳转到另一个页面
    8. }
    9. }
    10. </script>
  • search.html (传值) ```javascript

    搜索

``` #### 8.jquery-ajax 8-1 get ```javascript $.get(url,res=>{ console.log(res) }) $.get(url).then(res=>{ console.log(res) }) ``` 8-2 $.ajax ```javascript $.ajax({ url, type:"get", data, // get传值问号后面的值,可以放在data属性里面 dataType, success:res=>{ console.log(res); } }) ``` ```javascript var url ="http://192.168.4.18:3000/search" $.ajax({ url, type:"get", data:{ keywords:"你" }, success:res=>{ console.log(res); } }) ``` #### 9.axios ``` Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。 ``` 9-1 安装 ``` // 使用 npm $ npm install axios // 使用 bower $ bower install axios // 使用 cdn
  1. 9-2 get
  2. ```javascript
  3. axios.get(url).then(res=>{
  4. console.log(res);
  5. })
  1. // var url = "http://192.168.4.18:3000/search?keywords=你"
  2. axios.get("http://192.168.4.18:3000/search",{
  3. params:{
  4. keywords:"你"
  5. }
  6. }).then(res=>{
  7. console.log(res);
  8. })

9-3 axios

  1. axios({
  2. url,
  3. baseURL,
  4. method,
  5. params:{} //问号后面的值
  6. }).then(res=>{
  7. console.log(res)
  8. })
  1. axios({
  2. url:"/search",
  3. baseURL:"http://192.168.4.18:3000",
  4. method:"get",
  5. params:{
  6. keywords:"你"
  7. }
  8. }).then(res=>{
  9. console.log(res);
  10. })

9-4 axios二次封装

  1. var baseURL="http://192.168.4.18:3000/"
  2. function http({
  3. url,
  4. method:"get",
  5. params:{}
  6. }){
  7. return axios({
  8. url,
  9. baseURL,
  10. method,
  11. params
  12. })
  13. }
  1. http({
  2. url:"/album?id=96964667",
  3. }).then(res=>{
  4. console.log(res)
  5. })
  6. http({
  7. url:"/album",
  8. params:{
  9. id:"96964667"
  10. }
  11. }).then(res=>{
  12. console.log(res)
  13. })

10.ajax迭代

10-1 原生ajax

  1. var url = "http://192.168.4.18:8000/"
  2. var xhr = new XMLHttpRequest();
  3. xhr.open("get", url, true);
  4. xhr.send();
  5. xhr.onreadystatechange = function () {
  6. if (xhr.readyState == 4 && xhr.status == 200) {
  7. var result = JSON.parse(xhr.responseText);
  8. console.log(result)
  9. }
  10. }

10-2 回调函数去封装ajax

  1. // 需要记住传参的顺序
  2. function ajax(url,method="get",success) {
  3. var xhr = new XMLHttpRequest();
  4. xhr.open(method, url, true);
  5. xhr.send();
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState == 4 && xhr.status == 200) {
  8. var result = JSON.parse(xhr.responseText);
  9. success(result)
  10. }
  11. }
  12. }
  1. function ajax({
  2. url,
  3. method="get",
  4. success
  5. }) {
  6. var xhr = new XMLHttpRequest();
  7. xhr.open(method, url, true);
  8. xhr.send();
  9. xhr.onreadystatechange = function () {
  10. if (xhr.readyState == 4 && xhr.status == 200) {
  11. var result = JSON.parse(xhr.responseText);
  12. success(result)
  13. }
  14. }
  15. }

10-3 jquery-ajax

  1. $.ajax({
  2. url:"http://192.168.4.18:8000/",
  3. type:"get",
  4. dataType:"json",
  5. success:res=>{
  6. console.log(res)
  7. }
  8. })

10-4 callback封装jquery-ajax

  1. function http({url,type="get",success}){
  2. $.ajax({
  3. url,
  4. type,
  5. dataType:"json",
  6. success:res=>{
  7. success(rs)
  8. }
  9. })
  10. }

10-5 promise封装ajax
将纵向嵌套的ajax,变成横向的了,结构稍微清晰了一点。

  1. function http(url){
  2. return new Promise((resolve,reject)=>{
  3. $.ajax({
  4. url,
  5. type:"get",
  6. success:res=>{
  7. resolve(res)
  8. },
  9. error:err=>{
  10. reject(err);
  11. }
  12. })
  13. })
  14. }

11.回调地狱

  1. <div id="app"></div>
  2. <h2>列表数据</h2>
  3. <p class="dp"></p>
  4. <audio src="" controls></audio>
  5. <script>
  6. /* 1.华语中的第一条数据 */
  7. var url = 'http://192.168.4.18:3000/top/playlist/?cat=华语'
  8. $.ajax({
  9. url,
  10. success:res=>{
  11. var {name,id} = res.playlists[0]
  12. $("#app").html(name)
  13. /* 2.列表页数据 */
  14. var listUrl = `http://192.168.4.18:3000/playlist/detail?id=${id}`
  15. $.ajax({
  16. url:listUrl,
  17. success:res=>{
  18. var {name,id} = res.playlist.tracks[0]
  19. $(".dp").html(name)
  20. /* 3.根据id获取音乐播放器的url连接 */
  21. var musicUrl = `http://192.168.4.18:3000/song/url?id=${id}`
  22. $.ajax({
  23. url:musicUrl,
  24. success:res=>{
  25. let src = res.data[0].url
  26. $("audio").attr("src",src)
  27. }
  28. })
  29. }
  30. })
  31. }
  32. })
  33. </script>

12.promise

  1. Promise是一种异步操作的解决方案,将写法复杂的传统的回调函数和监听事件的异步操作,用同步代码的形式表达出来。
  2. 避免了多级异步操作的回调函数嵌套。
  3. promise本质:为了解决回调地狱问题
  1. <!-- promise 会将函数的状态暂停(凝聚,冻结)
  2. resolve -- 处理成功的情况
  3. reject -- 处理失败的情况
  4. promise不会直接触发,它会通过(then,catch)才会触发
  5. -->
  6. <!--
  7. 1.触发promiseresolve状态,可以then函数去触发
  8. 2.触发reject状态,通过catch函数去触发
  9. -->
  10. <script>
  11. var p = new Promise((resolve,reject)=>{
  12. //resolve(1)
  13. reject(2)
  14. })
  15. p.then(res=>{
  16. console.log(res);
  17. }).catch(err=>{
  18. console.log(err);
  19. })
  20. </script>

promise-ajax

  1. function http() {
  2. return new Promise((resolve,reject)=>{
  3. $.ajax({
  4. url:"http://192.168.4.18:3000/top/playlist/?cat=华语",
  5. type:"get",
  6. success:res=>{
  7. resolve(res)
  8. },
  9. error:err=>{
  10. reject(err)
  11. }
  12. })
  13. })
  14. }
  15. <script>
  16. http("top/playlist/?cat=华语").then(res=>{
  17. let id = res.playlists[0].id
  18. return id
  19. }).then(res=>{
  20. let id = res
  21. http(`playlist/detail?id=${id}`).then(res=>{
  22. var {name,id} = res.playlist.tracks[0]
  23. console.log(id);
  24. })
  25. })
  26. </script>

13.async-await

  1. /* async await */
  2. /*
  3. promise函数执行
  4. 1、then
  5. 2、在async函数中,通过await语句去执行
  6. */
  7. 在函数前面加上async
  8. 1.这个函数的返回值就是promise
  9. 2.可以在函数中使用await关键字
  1. var a = new Promise((resolve,reject)=>{
  2. setTimeout(()=>{
  3. resolve(1)
  4. },2000)
  5. })
  6. var b = new Promise((resolve,reject)=>{
  7. setTimeout(()=>{
  8. resolve(2)
  9. },1000)
  10. })
  11. async function go(){
  12. var res = await a;
  13. console.log(res);
  14. var sum = await b;
  15. console.log(sum);
  16. }
  17. go()