XMLHttpRequest 发送json 格式的数据,servlet 接收

XMLHttpRequest 实现的浏览器的HTTP异步的请求,在前后端进行数据交互的时候,常常使用json的数据格式,在最为基础的servlet 中来进行接收前台传入的json格式的数据,并且进行处理,下面介绍XMLHttpRequest发送数据和servlet 接收数据

javascript 复制代码
        const xhr=new XMLHttpRequest();
         let params=new FormData();
         let username=document.getElementById("username").value;
         let password=document.getElementById("password").value;
         xhr.open("post","./LoginServlet",true)
         xhr.setRequestHeader("Content-Type", "application/json"); 
        let param={
            "username":username,
            "password":password        
        }
        
        xhr.send(JSON.stringify(param));
        xhr.onreadystatechange=function(){
             console.log(xhr.readyState)
             console.log(xhr.responseText)
         
         }
      

后台接收servlet代码:

java 复制代码
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		StringBuilder sb=new StringBuilder();
		BufferedReader reader=request.getReader();
		String line=null;
		while((line=reader.readLine())!=null) {
		    sb.append(line);
		}
		System.out.println(sb.toString());
	}

上面就是前后端对应的代码,希望对你有所帮助!

相关推荐
鲸渔2 天前
【AI Agent系列课程13-Python 基础13】JSON 读写:结构化数据交换基础
开发语言·python·json·ai编程
aiotto资源分享5 天前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
一起学安全技术6 天前
拆大模型 10|结构化输出:让模型返回数据,而不是一段话
人工智能·语言模型·json
用户298698530146 天前
在 Python 中把 Word 文档转换为 JSON 的三种实现方式
python·json·api
FRing038 天前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
用户298698530148 天前
使用 Python 将 JSON 转换为 Word 文档的实践指南
python·json·api
九英里路8 天前
protobuf快速上手
网络·c++·中间件·json·谷歌·序列化·protobuf
wuyk5559 天前
Spider-第09讲-三格式落盘CSV-Excel-JSON
爬虫·python·json·excel
wuyk55510 天前
Spider-第07讲-JSON接口与正则提取
爬虫·python·json
xbzb12 天前
镜像到底存在哪:/var/lib/docker 的四级映射与 daemon.json 配置
docker·容器·json·镜像·daemon.json·四级