Ajax的常用方式在java web 中的开发的应用代码如下:
<%@ 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" src="js/Ajax_common.js"></script> </head> <body> First Name:<input type="text" id="txt1" /> <input type="button" name="mybutton" value="Ajax" οnclick="showHint(document.getElementById('txt1').value)"> </form>
<p>Suggestions: <span id="txtHint"></span></p>
</body></html>
ajax_commons.js的源代码的如下:
var xmlhttp=null; //创建xmlhttp对象的function createHttpObject(){ try{ xmlhttp=new XMLHttpRequest(); }catch(e){ //针对IE创建的xmlhttp对象的信息 try{ xmlhttp=ActiveXObject("Msxml2.XMLHTTP"); }catch(e) { try{ xmlhttp=ActiveXObject("Msxml2.XMLHTTP"); }catch(e) { } } } return xmlhttp;}
function showHint(username){ xmlhttp=createHttpObject(); if(xmlhttp==null) { alert("你的浏览器不支持的Ajax!"); return ; } //请求路径的 var url="./ajaxServlet?username="+username; //回调函数的应用 xmlhttp.onreadystatechange=stateChanged; //构建请求信息 xmlhttp.open("get",url,true); //发送请求信息 xmlhttp.send(null);}
//状态改变的设置的各种信息function stateChanged() { if (xmlhttp.readyState==4) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; }}
