<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
//当有关数据返回并且数据返回正确
if(xhr.readyState == 4 && xhr.status == 200){
console.log(JSON.parse(xhr.responseText));
}
}
xhr.open('POST','http://localhost:8080/ajax_test1_war_exploded/ajax')
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//post请求与fet请求携带参数方式是不一样的,需要将请求的参数放到send中
xhr.send('username=张安&password=1223&gender=M')
</script>
</html>
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String gender = req.getParameter("gender");
Map<String,String>map = new HashMap<>();
map.put("username",username);
map.put("password",password);
map.put("gender",gender);
String jsonStr = JSONObject.toJSONString(map);
resp.setContentType("application/json; charset=utf-8");
resp.setHeader("Access-Control-Allow-Origin", "*");
PrintWriter writer = resp.getWriter();
writer.write(jsonStr);
writer.flush();
writer.close();
}
网友评论