AJAx例子(post请求方式)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">var xmlHttpReq;//创建一个XmlHttpRequest对象function createXmlHttpRequest() {if (window.XMLHttpRequest) {xmlHttpReq = new XMLHttpRequest();//非IE浏览器} else if (window.ActiveXObject) {xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器}}function check(name){if(name!=""){alert(name);//1.创建一个XmlHttpRequest对象createXmlHttpRequest();//2.调用XMLHTTPRequest对象的 open方法(),//初始化XMLHttpRequest组件//处理缓存问题 url后面再加个时间参数,保证每次请求的url都不同var url = "validate";var query = "name="+name;xmlHttpReq.open("POST",url,true);// "Get"是请求方式,//url向后台服务器发送请求的url//true 代表使用异步请求, 可选参数,默认为true //3.注册回调函数xmlHttpReq.onreadystatechange=callBack;//callBack 为自定义的回调函数的名字 注意:后面没有括号//当xmlHttpReq对象的readystate状态改变时自动触发 回调函数callBack//4.把请求发送到服务器 xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttpReq.send(query); //post请求}else{alert("请输入数据");}}function callBack(){//alert("readyState:"+xmlHttpReq.readyState);if(xmlHttpReq.readyState==4){//ajax引擎初始化成功if(xmlHttpReq.status==200){//与tomcat(服务器)交互成功,http协议成功alert("xmlHttpReq.status:"+xmlHttpReq.status);var text = xmlHttpReq.responseText;//通过responseText 属性,取出服务器端返回的数据alert(text);}}}</script></head><body><p align="center">用户注册</p><table align="center"><tr><td>用户名</td><td><input type="text" ></td><td><span id="sp1"></span></td></tr></table></body></html>
页:
[1]