简单ajax入门。开发环境选择MyEclipse, 服务器tomcat, jsp处理后台任务。
搭建步骤:
- 在MyEclipse中新建project,例如MyAjax
- 在WebRoot下添加hello.jsp
- 修改index.jsp 以及 hello.jsp 如下
index.jsp
1 <html> 2 <head> 3 <title>Hello Ajax version 1</title> 4 <style type='text/css'> 5 * { 6 font-family: Tahoma, Arial, sans-serif; 7 } 8 9 #helloTitle { 10 color: #48f; 11 font-size: 1.5em; 12 } 13 </style> 14 <script type='text/javascript'> 15 window.onload = function() { 16 document.getElementById('helloBtn').onclick = function() { 17 var xhr; 18 var name = document.getElementById("helloTxt").value; 19 if (window.XMLHttpRequest) { 20 xhr = new XMLHttpRequest(); 21 } else { 22 xhr = new ActiveXObject("Microsoft.XMLHTTP"); 23 } 24 xhr.open("GET", "hello.jsp?name=" + name, true); 25 xhr.onreadystatechange = function() { 26 var ready = xhr.readyState; 27 if (ready == 4) { 28 var status = xhr.status; 29 if (status >= 200 && status < 300) { 30 31 alert(xhr.responseText); 32 } 33 } 34 } // end onreadstatechange 35 xhr.send(); 36 }; // end onclick 37 } 38 </script> 39 </head> 40 <body> 41 <h1 id='helloTitle'>Hello, stranger</h1> 42 <p>Please introduce yourself by entering your name in the box below</p> 43 <input type='text' size='24' id='helloTxt'></input> 44 <button id='helloBtn'>Submit</button> 45 </body> 46 </html>
hello.jsp
<%-- simple JSP to generate some questions - and answers--%> <jsp:directive.page contentType="text/plain"/> <% String name=request.getParameter("name"); System.out.print(name); %> Hello, <%=name%>
完成两个文件的修改后运行项目即可用ajax实现客户端与服务器的简单交互