日期:2014-05-16 浏览次数:20643 次
Ajax是目前比较流行的一种技术,比如在用户注册时,验证在用户名是否可以使用时,就用到了ajax技术,下面通过一个简单的例子来介绍如何使用ajax
ajax并不是一种新的技术,它其实异步的jacascript和xml
先将代码写上
<script type="text/javascript">
var xmlHttpRequest=null;
function ajaxSubmit()
{
if(window.ActiveXObject)
{
//说明当前使用的浏览器是ie
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}else if(window.XMLHttpRequest)
{
//当前使用的浏览器为非ie
xmlHttpRequest=new XMLHttpRequest();
}
if(xmlHttpRequest!=null)
{
xmlHttpRequest.open("POST", "AjaxServlet", true);
xmlHttpRequest.onreadystatechange=ajaxCall;
//如果使用post方法发送,下面这句必须要,get方式则不用
xmlHttpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//如果使用get方式发送,则参数直接放在servlet后面,在send方法中则传入nulll,post方法传送,则按如下规则使用
xmlHttpRequest.send("name=gavin");
}
}
function ajaxCall()
{
if(xmlHttpRequest.readyState==4)
{
if(xmlHttpRequest.status==200)
{
document.getElementById("div1").innerHTML=xmlHttpRequest.responseText;
}
}
}
</script>
在html页面中的body中添加如下html代码:
<body> <input type="button" value="Get Server Content" onclick="ajaxSubmit()"> <div id="div1"></div> </body>
最后添加一个Servlet
public class AjaxServlet extends HttpServlet
{
public void destroy()
{
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("invoke");
response.setContentType("text/html");
String name=request.getParameter("name");
PrintWriter out = response.getWriter();
out.print(name);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("POST");
this.doGet(request, response);
}
public void init() throws ServletException
{
// Put your code here
}
}
这个程序虽然简单,但是却可以将ajax的作用展现出来