Ajax前后端交互的方法
ajax简介
Ajax :“Asynchronous Javascript And XML”(异步 JavaScript 和 XML)
ajax的优点
无需重新加载整个网页的情况下,能够更新部分网页内容的技术
允许根据用户事件来更新部分网页内容
ajax的缺点
没有浏览历史,不能回退
存在跨域问题,只能访问同源网站内容(解决办法:jsonp/cors设置请求头)
SEO不友好
ajax的使用方法
方法一:原生ajax
创建对象:
constxhr=newXMLHttpRequest();设置请求方法:
xhr.open('GET','http://localhost:8000/server');发送请求:
xhr.send();处理服务端返回的结果
get方法发送原生ajax
//get方法发送原生ajaxconst btn = document.getElementsByTagName('button');<script>btn[0].onclick = function () {//创建对象const xhr = new XMLHttpRequest();//设置请求方法和urlxhr.open('GET', 'http://localhost:8000/server');//发送xhr.send();//事件绑定 处理服务端返回的结果xhr.onreadystatechange = function () {if (xhr.readyState === 4) { //服务端返回了所有结果if (xhr.status >= 200 && xhr.readyState <= 300) {//处理结果console.log(xhr.status); //状态码console.log(xhr.statusText); //状态字符串console.log(xhr.getAllResponseHeaders); //所有响应头console.log(xhr.response); //响应体result.innerHTML = xhr.response;} else {}}}}</script>
post方法发送原生ajax
//post方法发送原生ajax<script>btn[0].onclick = function(){const xhr = new XMLHttpRequest();xhr.open('POST', 'http://localhost:8000/server');//设置请求头xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');xhr.send('a=100&&b=200&&c=300');xhr.onreadystatechange = function(){if(xhr.readyState === 4){if(xhr.status >= 200 && xhr.status<300){result.innerHTML = xhr.response;}}};};</script>
原生ajax异常处理
//原生ajax异常处理,在xhr.open()之前//超时设置xhr.timeout = 2000;//超时回调xhr.ontimeout = function (){alert('网络异常,超时');};//网络异常回调xhr.onerror = function(){alert('网络异常');};//取消请求btns[1].onclick = function(){xhr.abort()};
方法二:jquery-ajax
使用前需要引入jquery的相关库
<script>//get方式,第四个参数为数据接收类型$('button').eq(0).click(function () {$.get('http://localhost:8000/jquery-server', { a: 100, b: 200 }, function (data) {console.log(data);}, 'json')});//poast方式$('button').eq(1).click(function () {$.post('http://localhost:8000/jquery-server', { a: 100, b: 200 }, function (data) {console.log(data);})});$('button').eq(2).click(function () {$.ajax({//urlurl: 'http://localhost:8000/jquery-server',//参数data: { a: 100, b: 200 },//请求类型type: 'GET',//响应体结果dataType: 'json',//成功的回调success: function (data) {console.log(data);},//超时时间timeout: 2000,//失败的回调error: function () {console.log('出错了');},//头信息设置headers: {c: 300,d: 400}})})</script>
方法三:axios-ajax
<script>const btns = document.querySelectorAll('button')btns[0].onclick = function () {//GET请求axios.get('http://localhost:8000/axios-server', {//url参数params: {id: 1000,vip: 10},//请求头信息headers: {name: 'hanser',age: '10'}}).then(value => {console.log(value);})}btns[1].onclick = function () {axios.post('http://localhost:8000/axios-server', {username: 'admin',password: '123'}, {//url参数params: {id: 1,vip: 123},//请求头参数headers: {name: 'younghd',age: '22'},//请求体...})}btns[2].onclick = function () {axios({method: 'POST',url: 'http://localhost:8000/axios-server',//url参数params: {vip: 10,id: 123},//头信息headers: {a: 100,b: 200},//请求体参数data: {name: 'younghd',age: '22'}}).then(response => {console.log(response);})}</script>
方法四:fetch-ajax
<script>const btn = document.getElementsByTagName('button');btn[0].onclick = function () {fetch('http://localhost:8000/fetch-server', {//请求方法method: 'POST',//请求头headers: {name: 'YoungHD'},//请求体body: 'name=admin&pd=password'}).then(Response => {console.log(Response);return Response.text();}).then(Response => {console.log(Response);})}</script>
服务器端:node.js-express
//1.引入express并创建应用对象const express = require('express');//2.创建应用对象const app = express();//3.创建路由规则//ajax-原生app.get('/server', (requrest, response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin', '*')//设置响应response.send('这是原生ajax');});//jquery-ajaxapp.all('/jquery-server', (requrest, response)=>{//设置允许自定义响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin', '*')response.setHeader('Access-Control-Allow-Headers', '*')const data = {name:'jquery-ajax'}//设置响应response.send(JSON.stringify(data))});//axios-ajaxapp.all('/axios-server', (requrest, response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin', '*')response.setHeader('Access-Control-Allow-Headers', '*')const data = {name:'axios-ajax'};//设置响应response.send(JSON.stringify(data));});//fetch-ajaxapp.all('/fetch-server', (requrest, response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin', '*')response.setHeader('Access-Control-Allow-Headers', '*')const data = {name:'fetch-ajax'};//设置响应response.send(JSON.stringify(data));});//4.监听端口app.listen(8000,()=>{console.log("服务已经启动,8080端口监听响应");});
