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

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

相关推荐
www_stdio1 天前
用 localStorage 打造本地待办清单:一个轻量级的前端实践
javascript·css·json
Jonathan Star2 天前
JSON-RPC 2.0 详解
qt·rpc·json
还算善良_2 天前
【XML生成】根据JSON格式化的报文,动态生成XML
xml·json
涛涛讲AI3 天前
被 JSON 格式折磨?1 个快捷键让 JSON-handle 秒启动,开发者必看!
json
韩仔搭建3 天前
Cocos Creator 项目配置 JSON 最佳实践
json
曼巴UE53 天前
JSON Reader
java·服务器·json
864记忆4 天前
Qt 对 JSON和XML文件的操作详解
xml·qt·json
x***01064 天前
使用 MySQL 从 JSON 字符串提取数据
mysql·oracle·json
咸甜适中5 天前
rust语言,将JSON中的所有值以字符串形式存储到sqlite数据库中(逐行注释)
数据库·rust·sqlite·json
Ustinian_3105 天前
【HTML】前端工具箱实现【文本处理/JSON工具/加解密/校验和/ASCII/时间戳转换等】【附完整源代码】
前端·html·json