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());
	}

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

相关推荐
譕痕1 天前
JSONObject与JSONArray封装数据格式区别
java·json
A黄俊辉A1 天前
uniapp webview中实现 app和内嵌的H5双向通信
vue.js·json
需要8261 天前
JVM 内存区域与对象创建:一次 GC 从哪来
java·jvm·spring boot·spring·servlet·tomcat
伞伞悦读1 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
Mikko72 天前
jackson-databind 升到 2.21.6 就安全了吗?jackson-core 是另一个坐标,它那条 high 全局库至今没收
java·后端·安全·json
天若有情6734 天前
独立开发复盘:我用 Node.js 做了个在线工具箱
前端·json·工具
Asurplus4 天前
【SpringBoot4】3、从SpringBoot4升级Sa-Token1.46.0报错
redis·sa-token·json·jackson·springboot4
代码中介商4 天前
C++ 预约系统实战(三):服务端实现——libevent 事件驱动与业务路由
c++·json·c/s
譕痕5 天前
notepad++安装插件 可视化展示 json串内容
json·intellij-idea
databook5 天前
DuckDB + SQL 高效分析 JSON 数据
数据分析·json·nosql