Ajax -- 发送 POST 请求

来源:互联网 发布:娶网络女主播 编辑:程序博客网 时间:2024/05/19 04:27
<body>     <center>            <button id="btn03">发送 POST 请求</button><br/>            <form action="AjaxRequestServlet" method="post">               <input type="text" name="username" /><input type="submit" value="submit" />             </form>     </center></body>

发送 POST 请求需要设置消息请求头(响应类型):Content-Type:application/x-www-form-urlencoded GET请求参数里有Content-Type:application/x-www-form-urlencode, 所以不需要设置

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><style type="text/css">button {width: 200px;}</style><script type="text/javascript">     function getRequest(){           //创建XMLHttpRequest 对象           var xmlHttpRequest = null;           try{//试用与主流浏览器                xmlHttpRequest = new XMLHttpRequest();           }catch(e){//适用于IE5、IE6                try{                     xmlHttpRequest = new ActiveXObejct("Microsoft.XMLHTTP");                }catch(e){                     alert("your browser not support Ajax!");                }           }           return xmlHttpRequest;     };     var request = getRequest();     //页面加载完成后加载     window.onload = function(){           document.getElementById("btn03").onclick = function(){                //发送 POST 请求                //发送请求参数: 将请求参数键值对以参数形式传递给 send 方法                //设置请求消息头: Content-Type:application/x-www-form-urlencoded                request.open("POST", "AjaxRequestServlet", true, "admin", "admin");                request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");                request.send("username=Jerry");           };     };</script></head>
package com.atguigu.ajax.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/AjaxRequestServlet")public class AjaxRequestServlet extends HttpServlet {    private static final long serialVersionUID = 1L;    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //获取请求断传入的参数        String username = request.getParameter("username");        System.out.println("AjaxRequestServlet.doGet()  username: " + username);    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        System.out.println("AjaxRequestServlet.doPost() username: " + request.getParameter("username"));    }}
原创粉丝点击