ajaxPOST

作者: 愤青还是奋青 | 来源:发表于2020-04-27 08:45 被阅读0次
    <!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();
    
    }
    

    相关文章

      网友评论

          本文标题:ajaxPOST

          本文链接:https://www.haomeiwen.com/subject/aavczttx.html