AJAX案例一:发送POST请求
2016-11-20 20:19
302 查看
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 4 <html> 5 <head> 6 <meta http-equiv="pragma" content="no-cache"> 7 <meta http-equiv="cache-control" content="no-cache"> 8 <meta http-equiv="expires" content="0"> 9 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 10 <meta http-equiv="description" content="This is my page"> 11 <script type="text/javascript"> 12 function createXMLHttpRequest() { 13 try { 14 return new XMLHttpRequest(); 15 } catch (e) { 16 try { 17 return ActvieXObject("Msxml2.XMLHTTP"); 18 } catch (e) { 19 try { 20 return ActvieXObject("Microsoft.XMLHTTP"); 21 } catch (e) { 22 alert("用的是什么浏览器啊?"); 23 throw e; 24 } 25 } 26 } 27 } 28 window.onload = function() { 29 var btn = document.getElementById("btn"); 30 btn.onclick = function() { 31 var xmlHttp = createXMLHttpRequest(); 32 //修改为POST请求方式 33 xmlHttp.open("POST", "<c:url value='/AServlet'/>", true); 34 //POST请求要设置请求头 35 xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 36 //添加参数 37 xmlHttp.send("username=张三&password=123"); 38 xmlHttp.onreadystatechange = function() { 39 if(xmlHttp.readyState == 4 && xmlHttp.status == 200) { 40 var text = xmlHttp.responseText; 41 var h1 = document.getElementById("h1"); 42 h1.innerHTML = text; 43 } 44 }; 45 }; 46 }; 47 </script> 48 </head> 49 <body> 50 <button id="btn">点击这里</button> 51 <h1 id="h1"></h1> 52 </body> 53 </html>
1 import java.io.IOException; 2 import javax.servlet.ServletException; 3 import javax.servlet.http.HttpServlet; 4 import javax.servlet.http.HttpServletRequest; 5 import javax.servlet.http.HttpServletResponse; 6 public class AServlet extends HttpServlet { 7 public void doPost(HttpServletRequest request, HttpServletResponse response) 8 throws ServletException, IOException { 9 //处理编码问题,防止乱码 10 response.setContentType("text/html;charset=utf-8"); 11 request.setCharacterEncoding("UTF-8"); 12 String username = request.getParameter("username");//获取请求参数 13 response.getWriter().print(username+"已注册"); 14 } 15 }
相关文章推荐
- 使用原生ajax发送post请求完整案例
- Ajax详解及其案例分析之如何获得Ajax对象,使用Ajax对象发送GET和POST请求,校验用户名,POST和GET请求时的乱码处理,实现级联的下拉列表
- Ajax发送GET、POST请求和响应XML数据案例
- 发送Ajax(get、post)请求时设置为异步
- $.ajax ie中发送post请求不成功
- Js/Ajax中发送HttpPost请求调用WebService
- Extjs的ajax同步请求时post方式参数发送方式
- ajax发送get、post请求
- POST方式发送ajax请求详解
- jquery ajax/post 请求 案例
- POST方式发送ajax请求详解
- JS将form表单转换为json数据,使用ajax发送请求案例
- Extjs ajax同步请求时post方式参数发送方式
- AJAX第二例(发送POST请求)
- django中input type=submit 发送ajax 的post和get请求
- Ajax学习第二节_发送post请求
- ajax初步学习发送post请求
- Ajax的GET与POST方式向服务器发送请求
- Django用ajax发送post请求时csrf拦截的解决方案
- jquery中使用ajax发送post请求返回数据在error中