当前位置: 首页 > Web前端 > HTML5

js调用后台数据的方法总结(包括原生js、ajax、websocket、axios、nodeJS等)

时间:2023-04-05 20:44:19 HTML5

1.js原生//转义特殊字符functionfilter(str){str+='';//隐式转换str=str.replace(/%/g,'%25');str=str.replace(/\+/g,'%2B');str=str.replace(//g,'%20');str=str.replace(/\//g,'%2F');海峡=海峡。替换(/\?/g,'%3F');str=str.replace(/&/g,'%26');str=str.replace(/\=/g,'%3D');str=str.replace(/#/g,'%23');returnstr;}//js格式对象作为url参数functionformateObjToParamStr(paramObj){varsdata=[];for(varattrinparamObj){sdata.push(attr+'='+filter(paramObj[attr]));}returnsdata.join('&');}//创建ajax请求函数createXMLHttpRequest(url,type,params,callback){varxhr=null;//1.首先创建一个XMLHttpRequest请求if(window.XMLHttpRequest){//主流浏览器xhr=newXMLHttpRequest();}elseif(window.ActiveXObject){//低版本IE浏览器(IE5和IE6)xhr=newActiveXObject("Microsoft.XMLHTTP");}if(xhr!=null){if(type.toLowerCase()=='get'){//2.请求行(请求方法和请求地址),get请求需要拼接url后面的参数xhr.open(type,url+'?'+formateObjToParamStr(params));//4.Requestbody(send发送请求),getrequestSendnullxhr.send(null);}elseif(type.toLowerCase()=='post'){//2.请求行(请求方法和请求地址)xhr.open(type,url);//3.Requestheader,仅用于post请求xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//4.Requestbody(send发送请求),postrequest需要把参数放在send()中,xhr.send(formateObjToParamStr(params));}//5.监听状态变化xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){//6.接收返回数据//请求成功回调(xhr.response)}else{//请求失败}}};}else{alert("您的浏览器不支持XMLHTTP");}}//使用createXMLHttpRequest('https://www.baidu.com/cache/aladdin/ui/tabs5/tabs5.js','get',{v:20170208},function(data){document.body.innerHTML=data;});2.jquery的ajaxletparams={name:'qinghuo',age:18};$.ajax({url:'https://www.baidu.com',type:'post',async:true,data:params,成功:function(res){console.log('后台返回数据'+res.data)},错误:function(){console.log('接口请求失败')}});3.HTML5websocket函数WebSocketTest(){if("WebSocket"inwindow){console.log("您的浏览器支持WebSocket!");//打开一个网络套接字varws=newWebSocket("ws://localhost:9998/echo");ws.onopen=function(){//WebSocket已经On连接,使用send()方法发送数据ws.send("sendingdata");console.log("数据正在发送中...");};ws.onmessage=function(evt){varreceived_msg=evt.数据;console.log("数据收到...");};ws.onclose=function(){//关闭websocketconsole.log("Connectionclosed...");};}else{//浏览器不支持WebSocketalert("您的浏览器不支持WebSocket!");}}4.vue的axiosget请求//为给定ID的用户创建请求axios.get('/user?ID=12345').then(function(response){console.log(response);}).catch(function(error){console.log(error);});//可选的,上面的请求可以这样做axios.get('/user',{params:{ID:12345}}).then(function(响应){console.log(response);}).catch(function(error){console.log(error);});post请求axios.post('/user',{name:'qinghuo',age:18}).then(function(response){console.log(response);}).catch(function(error){console.日志(错误);});5.nodejshttp模块consthttp=require("http");constpostData=JSON.stringify({name:"qinghuo",age:"18"});//data=require('querystring').stringify(data);constoptions={hostname:'www.google.com',port:80,path:'/upload',method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded}','内容长度':Buffer.byteLength(postData)}};constreq=http.request(options,(res)=>{console.log(`statuscode:${res.statusCode}`);console.log(`responseheader:${JSON.stringify(res.headers)}`);res.setEncoding('utf8');res.on('data',(chunk)=>{console.log(`Responsebody:${chunk}`);});res.on('end',()=>{console.log('响应中没有更多数据。');});});req.on('error',(e)=>{console.error(`请求遇到问题:${e.message}`);});//向请求体写入数据req.write(postData);req.end();