<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>fetch</title>
<meta name="Keywords" content="关键字">
<meta name="description" content="简介">
</head>
<body>
<!-- fetch 实现ajax -->
<h3 id="tt"></h3>
<script>
/*//fetch ajax get 并获取服务器的文本字符串.text()
fetch("/fetch?id=1&name=徐龙象")
.then(res=>res.text())
.then(msg=>{
document.querySelector("#tt").innerHTML=msg;
})*/
//fetch post
/*转json字符串 JSON.stringify()*/
fetch("/fetch",{
method:"post",
body:"id=1&name=徐凤年",
headers:new Headers({"Content-Type":"application/x-www-form-urlencoded"})
})
.then(res=>res.json())
.then(msg=>{
console.log(msg)
})
</script>
</body>
</html>
Fetch的get和post请求
package ws.wsj.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @author 卋舉
* @ProjectName IntelliJ IDEA
* @ClassName Fetch
* @description: TODO
* @date 2021/10/20 9:44
*/
@WebServlet("/fetch")
public class Fetch extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String info = String.format("get-method:%s,hello world",req.getMethod());
System.out.println(req.getParameter("id"));
System.out.println(req.getParameter("name"));
resp.getWriter().println(info);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器输出乱码问题
//解决post请求,中文乱码
req.setCharacterEncoding("utf-8");
String info = String.format("post - method:%s,hello world",req.getMethod());
System.out.println(req.getParameter("id"));
System.out.println(req.getParameter("name"));
resp.getWriter().println(info);
}
}