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

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

相关推荐
huohuopro1 天前
Servlet概述
servlet
ID_180079054732 天前
小红书笔记详情 API 接口系列 + 标准 JSON 返回参考(完整版)
数据库·笔记·json
恼书:-(空寄2 天前
拦截器获取不到 POST 请求 JSON 结构体参数(完整解决方案)
java·spring boot·spring·servlet
小狗丹尼4002 天前
JSON 基础认知、数据转换与 Flask 前后端交互全解
python·flask·json
奔跑的呱呱牛2 天前
arcgis-to-geojson双向转换工具库
arcgis·json
武超杰2 天前
SpringMVC核心功能详解:从RESTful到JSON数据处理
后端·json·restful
还是大剑师兰特3 天前
Vue3 前端专属配置(VSCode settings.json + .prettierrc)
前端·vscode·json
qq_283720053 天前
Cesium实战(三):加载天地图(影像图,注记图)避坑指南
json·gis·cesium
雷帝木木3 天前
Flutter for OpenHarmony:Flutter 三方库 cbor 构建 IoT 设备的极致压缩防窃协议(基于标准二进制 JSON 表达格式)
网络·物联网·flutter·http·json·harmonyos·鸿蒙
长安11083 天前
JsonCpp的编译与使用
json