【Ajax】全详解

1.Ajax的特点

AJAX 的优点

 可以无需刷新页面而与服务器端进行通信

 允许你根据用户事件来更新部分页面内容

AJAX 的缺点

 没有浏览历史,不能回退

 存在跨域问题(同源)

 SEO 不友好

2.发送get / post 请求

页面:

复制代码
const btn=document.getElementsByTagName("button")[0]
const result=document.getElementById('result')
     //发送get请求 btn.onclick
=function (){ //创建对象 const xhr=new XMLHttpRequest() //发给谁 xhr.open('GET','http://localhost:9000/server') xhr.send() xhr.onreadystatechange=function (){ if(xhr.readyState===4){ if(xhr.status>=200&&xhr.status<305){ let msg=xhr.status+' '+xhr.statusText+' ' + xhr.getAllResponseHeaders()+' '+xhr.response result.innerHTML=msg; } } } }
     //发送post请求 result.addEventListener(
'mouseover',function () { const xhr=new XMLHttpRequest() xhr.open('POST','http://localhost:9000/server') xhr.send('123456') xhr.onreadystatechange=function (){ if(xhr.readyState===4){ if(xhr.status>=200&&xhr.status<305){ result.innerHTML=xhr.response } } } })
复制代码

服务器:

复制代码
const express=require('express')
const app=express()
app.get('/server',
    (req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','*');
    res.send('hello server get');
});
app.post('/server',
    (req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','*');
    res.send('hello server post');
});

app.listen(9000,(err)=>{
    if(!err){
        console.log('启动成功server')
    }
})
复制代码

3.请求超时、网络异常和请求取消

复制代码
//设置响应时间
xhr.timeout=2000;
//设置请求超时回调
xhr.ontimeout = function(){
    console.log('超时')
}
//设置网络异常回调
xhr.onerror = function(){
    console.log('网络异常')
}
//手动取消,可以借助这个实现重复发送请求问题
xhr.abort
()
复制代码

4. jQuery发送Ajax请求

发送get请求:

  $.get( url , [data] , [callback] , [type])

发送post请求:

  $.post( url , [data] , [callback] , [type])

url:请求的URL 地址

data:请求携带的参数

callback:载入成功时回调函数

type:设置返回内容格式,xml, html, script, json, text, _default

通用方法发送:

$.ajax({

 url:.......

 data:.......

 type:.......

 dataType:.......

 success:.......

 timeout:.......

 error:.......

 headers:{  

  a:.......

  b:.......

})

 5.axios发送Ajax请求(多数用这个)

可以将url设置在这里

axios.defaults.baseURL='url'

发送 get / post请求:

axios.get( '/axios-server' , {

 //url参数

 params:{

  a:''

  b:''

 },

 //请求头信息

 headers:{

  name:''

 }

}).then(value =>{});

通过axios函数发送请求(大体一致,就是将url和请求类型写入对象中):

axios({

 //type

 method :'get'

 //url

 url:'axios-server' ,

 //url参数

 params:{

  a:''

  b:''

 },

 //请求头信息

 headers:{

  name:''

 }

}).then(value =>{});

6.用fetch函数发送Ajax请求(用的较少,了解就好)

fetch( 'url' , {

 //type

 method :'get'

 //请求头信息

 headers:{

  name:''

 }

 //请求体

 body:'username=123&password=123',

}).then(response=>{});

7.跨域

同源策略:

同源策略(Same-Origin Policy)最早由Netscape 公司提出,是浏览器的一种安全策略

同源: 协议、域名、端口号必须完全相同

跨域: 违背同源策略就是跨域

解决跨域1 JSONP(非官方):

在网页有一些标签天生具有跨域能力,比如:img link iframe script。JSONP 就是利用script 标签的跨域能力来发送请求的。只支持 get 请求

 示例:<script src="http://locahost:9000/jsonp-server" ></script>

http://localhost: + 端口号 + / + 请求信息

解决跨域2 CORS(官方):

CORS(Cross-Origin Resource Sharing),跨域资源共享。CORS 是官方的跨域解决方案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get 和post 请求。跨域资源共享标准新增了一组HTTP 首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源。CORS 是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后就会对响应放行。

示例:response.setHeader('Access-Control-Allow-Origin','*')

posted @   RikkaXl  阅读(229)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示