码迷,mamicode.com
首页 > Web开发 > 详细

最初级的ajax程序

时间:2018-03-16 22:01:43      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:发送请求   htm   generate   round   ima   title   eva   一个   alert   

该文章实现的ajax功能是实现了在<span>上面添加内容

 jsp代码

<html>
<head>
<title>Ajax</title>
</head>
<script type="text/javascript">
//1写一个得到XMLHttpRequest对象的函数
function createXHR() {
var xhr = null;
if (window.ActiveXObject) {
xhr = new ActiveXObject("microsoft.xmlhttp");
} else {
xhr = new XMLHttpRequest();
}
return xhr;
}
//2写一个函数让标签来调用
function writeValue() {
alert("fausf");

//3创建ajax引擎对象
var xhr = createXHR();
//4创建ajax状态监听
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//接受返回字符串
msg = xhr.responseText;
//使用返回的字符串信息
document.getElementById("txt").innerHTML = msg;
}
}
};
//5准备以get方式发送请求
xhr.open("get", "/Ajaxdemo/AServlet?time=" + new Date().getTime());
//设置为 post时,就可以在send函数中添加参数列表。当为get时,下面的send中参数为null。
xhr.send(null);
}
</script>
<body>
<input type="submit" onclick="writeValue();">
<span id="txt"></span>
</body>
</html>

Servlet代码

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub

//必须设置返回文件类型下面为html,还有一种是xml
response.setContentType("text/html;charset=utf-8");
response.getWriter().write("nihao");

 

运行截图

技术分享图片

 




 

最初级的ajax程序

标签:发送请求   htm   generate   round   ima   title   eva   一个   alert   

原文地址:https://www.cnblogs.com/fdbk/p/8585727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!