标签:const xhr server 响应 result 数据 response 服务端 客户端
3-JSON.html('手动转换'由服务端发来的数据)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Json响应</title> <style> #result{ width:200px; height:100px; border:solid 1px #4fad09; } </style> </head> <body> <div id="result"></div> <script> //获取元素对象 const result=document.getElementById('result'); //绑定键盘按下事件 window.onkeydown=function(){ //发送请求 const xhr=new XMLHttpRequest(); //初始化 xhr.open('GET','http://127.0.0.1:8000/json-server'); //发送 xhr.send(); //事件绑定 xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.status>=200 && xhr.status<300){ // console.log(xhr.response); // result.innerHTML=xhr.response; //手动对数据转化 let data=JSON.parse(xhr.response); console.log(data); result.innerHTML=data.name; } } } } </script> </body> </html>
3-JSON.html('自动转换'由服务端发来的数据)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Json响应</title> <style> #result{ width:200px; height:100px; border:solid 1px #4fad09; } </style> </head> <body> <div id="result"></div> <script> //获取元素对象 const result=document.getElementById('result'); //绑定键盘按下事件 window.onkeydown=function(){ //发送请求 const xhr=new XMLHttpRequest(); //设置响应体数据的类型 xhr.responseType='json'; //初始化 xhr.open('GET','http://127.0.0.1:8000/json-server'); //发送 xhr.send(); //事件绑定 xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.status>=200 && xhr.status<300){ // console.log(xhr.response); // result.innerHTML=xhr.response; //自动对数据转化 console.log(xhr.response); result.innerHTML=xhr.response.name; } } } } </script> </body> </html>
服务端server.js
//1.引入express const express=require('express'); //2.创建应用对象 const app=express(); //3.创建路由规则 //request是对请求报文的封装 //response是对响应报文的封装 app.get('/server',(request,response)=>{ //设置响应头 允许跨域 response.setHeader('Access-Control-Allow-Origin','*'); //设置响应体 response.send('Hello Ajax GET'); }); app.all('/server',(request,response)=>{ //设置响应头 允许跨域 response.setHeader('Access-Control-Allow-Origin','*'); //响应头 response.setHeader('Access-Control-Allow-Headers','*'); //设置响应体 response.send('Hello Ajax POST'); }); app.all('/json-server',(request,response)=>{ //设置响应头 允许跨域 response.setHeader('Access-Control-Allow-Origin','*'); //响应头 response.setHeader('Access-Control-Allow-Headers','*'); //响应一个数据 const data={ name:'atguigu' }; //对对象进行字符串转换 let str=JSON.stringify(data); //设置响应体 response.send(str); }); //4.监听端口启动服务 app.listen(8000,()=>{ console.log("服务已经启动,8000端口监听中......"); })
页面效果:(键盘按下任意键,控制端都会返回如下结果,绿框中显示从服务端接收的数据)
标签:const,xhr,server,响应,result,数据,response,服务端,客户端 来源: https://www.cnblogs.com/eisenshu/p/15855243.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。