您的位置:首页 > Web前端 > JavaScript

ajax helloworld jsp ajax入门,后台使用jsp

2012-11-26 17:12 155 查看
简单ajax入门。开发环境选择MyEclipse, 服务器tomcat, jsp处理后台任务。

搭建步骤:

在MyEclipse中新建project,例如MyAjax

在WebRoot下添加hello.jsp

修改index.jsp 以及 hello.jsp 如下

index.jsp

<html>
<head>
<title>Hello Ajax version 1</title>
<style type='text/css'>
* {
font-family: Tahoma, Arial, sans-serif;
}

#helloTitle {
color: #48f;
font-size: 1.5em;
}
</style>
<script type='text/javascript'>
window.onload = function() {
document.getElementById('helloBtn').onclick = function() {
var xhr;
var name = document.getElementById("helloTxt").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "hello.jsp?name=" + name, true);
xhr.onreadystatechange = function() {
var ready = xhr.readyState;
if (ready == 4) {
var status = xhr.status;
if (status >= 200 && status < 300) {

alert(xhr.responseText);
}
}
} // end onreadstatechange
xhr.send();
}; // end onclick
}
</script>
</head>
<body>
<h1 id='helloTitle'>Hello, stranger</h1>
<p>Please introduce yourself by entering your name in the box below</p>
<input type='text' size='24' id='helloTxt'></input> 
<button id='helloBtn'>Submit</button>
</body>
</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实现客户端与服务器的简单交互
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐