AJAX笔记分享

Posted 多酞科技

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX笔记分享相关的知识,希望对你有一定的参考价值。

1. 基础

1.

请求报文

行      POST或GET  /s?ie=utf-8  HTTP/1.1 
Host: atguigu.com
Cookie: name=guigu
Content-type: application/x-www-form-urlencoded
User-Agent: chrome 83
空行
体 username=admin&password=admin

2.

响应报文

行      HTTP/1.1  200  OK
头 Content-Type: text/html;charset=utf-8
Content-length: 2048
Content-encoding: gzip
空行
<html>
<head></head>
<body>
<h1>尚硅谷</h1>
</body>
</html>
响应状态码xhr.status 含义 xhr.readystate 含义
200-300 OK 0 未初始化
401 未授权 1 open调用完毕
403 禁止 2 send调用完毕
404 找不到 3 已返回部分结果
500 内部错误 4 已返回全部结果

3.

在js端的设置

// 1. 引入express
const express = require('express')
// 2. 创建应用对象
const app = express()

// 3. 创建路由规则 require是对请求报文对封装 response是对响应报文的封装
//1.get 请求
app.get('/server',(request,response)=>{
// 设置响应头 设置允许跨域 *为适配所有网页
response.setHeader('Access-Control-Allow-Origin','*')
// 允许自定义头信息,*为允许所有的自定义头信息,
response.setHeader('Access-Control-Allow-Headers','*')
// 允许自定义头方法,*为允许所有的自定义头方法,
response.setHeader('Access-Control-Allow-Headers','*')
// 设置响应
response.send('hello ajax 为GET请求')
})
//2. get和pose请求均可,返回json字符串
app.all('/all',(request,reponse)=>{
response.setHeader('Access-Control-Allow-Origin','*')
const data = { name : 'wuhu',age:'hh',sex:'1',pot:'bj'}
response.send(data)
})

// 4.监听端口
app.listen(8000,()=>{
console.log('服务已启动,8000')
})
 使用方法:在终端输入node 文件名.后缀,在浏览器输入127.0.0.1:8000/server

4.

安装nodemon服务方法(自动重启js的服务)

需要已经安装nodejs程序右键需要安装的js打开终端输入 sudo npm install -g nodemon(win不需要输入sudo)之后需要开启自动重启功能,输入nodemon server.js 即可

5.

HTML端的设置

1.

监听事件,调用js

document.querySelector('.box').addEventListener('click',funcrion(){ 此处写ajax的js代码 })
2.

创建对象,初始化

const xhr = new XMLHttpRequest()
xhr.open('post','http://127.0.0.1:8000/server')
xhr.responseType = 'json'
xhr.timeout = 2000 //超过2000毫秒即为异常
xhr.ontimeout = function(){
alert('网络异常呀呀呀呀呀') }
xhr.onerror = function(){
alert('网络有问题啊啊啊啊') }

设置请求类型get/post 和 URL端口;并设置返回值当数据类型为json(会自动转化为对象)

3.

设置请求头

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
4.

发送

xhr.send('a=100&b=200&c=20')

变量之间使用&分开,可以写=也可以写:

5.

事件绑定

xhr.onreadystatechange = function(){
if(xhr.readyState === 4){ //当返回全部结果时
if(xhr.status >=200 && xhr.status <300){ //当状态码为2xx(正常)时
//执行操作
console.log(xhr.response.name)//打印返回值中的name
}
}
}
6.

取消请求

btn.onclick = function(){
x.abort()} //取消请求





6.

各种其他方法调用

1.

jQuery调用

$("button").click(function(){
$.ajax({
// 设置url
url:'http://127.0.0.1:8000/jquery-server',
// 设置传入参数
data:{a:200,b:300},
// 设置相应体类型
type:'GET',
// 设置相应体结果类型
dataType:'json',
// 成功的回掉
success:function(data){ },timeout:2000,
// 失败的回掉
error:function(){ },
})
})

2.

axios调用

方法1

$('button').click(function(){
axios({
// 请求方法
method:'POST',
// URL
url:'http://172.0.0.1:8000/axios',
// URL参数
params:{
name:tsja,
level:6},
// 头信息
headers:{
a:100,
b:200},
// 请求参数
data:{
name:tsja,
pasword:111111},
// 成功后的回掉函数
}).then(Response=>{
console.log('wuhu')
})
})

方法2

$('button').click(function(){
axios.get('http://127.0.0.1:8000/axios-server',{
// url参数
params:{
id:100,
vip:7
},
// 请求头信息
headers: {
name:'atguigu',
age:20
}
}).then(value=>{ //回掉函数
console.log('wuhu')
})
})





3.

fetch调用

//传入url和参数
fetch('http://127.0.0.1:8000/fetch-server?vip=10',{
// 请求方法
method:'POST',
// 请求头
headers:{neme:'wuhu'},
// 请求体
body:'user=wuhu&age-11'
}).then(response=>{
// .json输出对象, .text输出字符串
return response.json()
}).then(response=>{
//可以跟多个回掉函数
})




2. 跨域 jsonp

1.

原理

ajax默认协议域名端口一致才能传输,跨域即为克服此问题

实现原理:不同端口无法传递数据,但可以调用函数,将数据放到函数实参中传递即可跨域



2.

原生jsonp

1.

先声明跨域用的函数

<script>
function wuhu(data){ console.log(data.name) }
</script>

2.

script标签引入服务

<script src="http://127.0.0.1:8000/jsonp"></script>

3.

配置js服务

app.all('/jsonp',(request,response)=>{
// 设置要跨域返回的对象
const data = {name:'wuhu',age:'12'}
// 将对象转换为字符串
let str = JSON.stringify(data)
// 将字符串作为函数的参数返回,即可跨域传递内容
response.end(`wuhu(${str})`)
})





3.

jQuery操作jsonp

1.

html部分 注:url后面要写?callback=?

$.getJSON('http://127.0.0.1:8000/jquery?callback=?',function(data){
console.log(${data.name})
})

2.

js部分

app.all('/jquery',(request,response)=>{
const data = {name:'wuhu'}
// 数据转化为字符串
let str = JSON.stringify(data)
// 接受callback参数
let cb = request.query.callback
// 返回结果
response.end(`${cb}(${str})`)
})

3.

解释:jq传入函数时,callback会被随机赋值,使用request.query.callback极为获取随机的函数名,用于jsonp跨域





4.

cors获取jsonp(正规军)

1.

html部分和正常ajax一摸一样

const x = new XMLHttpRequest();
x.open('GET','http://127.0.0.1:8000/cors')
x.send()
x.onreadystatechange = function(){
if(x.readyState === 4){
if(x.status >=200 && x.status<300){
console.log(x.response)}
}
}

2.

js部分加入允许跨域代码即可

// 设置响应头 设置允许跨域 *为适配所有网页
response.setHeader('Access-Control-Allow-Origin','*')
// 允许自定义头信息,*为允许所有的自定义头信息,
response.setHeader('Access-Control-Allow-Headers','*')
// 允许自定义头方法,*为允许所有的自定义头方法,
response.setHeader('Access-Control-Allow-Headers','*')




以上是关于AJAX笔记分享的主要内容,如果未能解决你的问题,请参考以下文章

微信小程序代码片段

02 - Unit07:显示笔记下拉菜单笔记的分享功能笔记的删除功能

AJAX相关JS代码片段和部分浏览器模型

vuejs学习笔记--属性,事件绑定,ajax

vuejs学习笔记--属性,事件绑定,ajax

vuejs学习笔记--属性,事件绑定,ajax