服务器端响应的数据格式
JSON.parse()//将json字符串转换为json对象
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <script type="text/javascript"> 9 var xhr=new XMLHttpRequest(); 10 xhr.open(‘get‘,‘http://localhost:3000/responseData‘); 11 xhr.send(); 12 xhr.onload=function(){ 13 console.log("1 "+xhr.responseText)//{"name":"zs"} 14 console.log("2 "+typeof xhr.responseText)//string类型 15 16 var responseText3=JSON.parse(xhr.responseText)//将JSON字符串转换为JSON对象 17 console.log("3 "+responseText3)//[object Object] 18 19 var str=‘<h2>‘+responseText3.name2+‘</h2>‘ 20 document.body.innerHTML=str; 21 } 22 </script> 23 </body> 24 </html>
//引入express框架 const express=require(‘express‘) //引入路径处理模块 const path=require(‘path‘) //创建web服务器 const app=express(); //静态资源访问服务器功能 app.use(express.static(path.join(__dirname,‘public‘))) //对应01html文件 app.get(‘/first‘,(req,res)=>{ res.send(‘Hello Ajax‘); }); // app.get(‘/responseData‘,(req,res)=>{ res.send({"name2":"zs"}); }); //监听端口 app.listen(3000); //控制台提示输出 console.log(‘服务器启动成功2‘)
原文:https://www.cnblogs.com/technicist/p/12739588.html