您的位置:首页 > 其它

AJAX

2016-07-01 10:04 337 查看
摘要: 最近学习了JS,用JS实现了Ajax

1. 在eclipse创建一个动态web项目

2. 创建一个ajaxPost.html,内容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//创建XMLHttpRequest对象
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { //浏览器兼容性

xmlhttp = new XMLHttpRequest();
} else { //兼容iE6一下的版本
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//结果返回后,页面处理
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
//发送请求
xmlhttp.open("post", "demoPost.jsp", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xmlhttp.send("city=北京&name=xiaohua");
}
</script>

</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html>

3. 再创建一个接受请求的demoPost.jsp,内容如下:

<%
//设置编码方式
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String fname=request.getParameter("name");
String fcity=request.getParameter("city");
out.print("Dear " + fname + ".");
out.print("Hope you live well in " + fcity + ".");
%>

4. 启动Tomcat,在浏览器中输入:http://localhost:8080/AJAX/ajaxPost.html,回车可以看到下面信息:



5. 点击“请求数据”按钮,我们看到有数据返回到页面上来了,详见下图:



6. AJAX的具体实现见文章粗体部分。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: