ajax发送POST请求

发送请求需要带有参数,一般都是POST请求

第一个参数改成post

xmlHttp.open("PSET","/test1/ZServlet",true);

添加一步:设置Content-Type请求头

xmlHttp.setRequestHeader("Content-Type","appliction/x-www-form-urlencoded");

请求示例

xmlHttp.send("username=zhangSan&password=123");

XServlet

package com.forcoldplay.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class XServlet
 */
public class XServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public XServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        System.out.println("(POST1:) Hello AJAX");

        response.getWriter().print("(POST2:) Hello AJAX");
    }

}
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function createXMLHttpRequest() {
    try {
        return new XMLHttpRequest() ;
    } catch (e){
        try{
            return ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                return ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("你用的浏览器我实在没办法搞");
                throw e;
            }
        }
    }
}
window.onload = function() {
    var btn = document.getElementById("btn");
    btn.onclick = function() {    //给按钮的点击事件添加监听
        //使用ajax得到服务器响应
        var xmlHttp = createXMLHttpRequest();
    
        xmlHttp.open("POST","/test1/XServlet",true);
    
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        
        xmlHttp.send("username=zhangSan&password=123");
        xmlHttp.onreadystatechange = function() {
            if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
                //获取服务器的响应结果
                var text = xmlHttp.responseText;
                //获取h1元素
                var h1 = document.getElementById("h1");
                
                h1.innerHTML = text ;
            }
        };
    }
}
</script>
</head>
<body>
<%--点击按钮之后,把服务器响应的数据显示到h3元素中 --%>
<button id = "btn">点击这里</button>
<h1></h1>
<h3 id = "h3"> </h3>
</body>
</html>
Last modification:February 12th, 2020 at 09:00 pm
如果觉得我的文章对你有用,请随意赞赏