最初级的ajax程序

Posted 锋_锋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了最初级的ajax程序相关的知识,希望对你有一定的参考价值。

该文章实现的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程序的主要内容,如果未能解决你的问题,请参考以下文章

ChatGPT无法替换最初级的程序员

java初级程序员面试点持续更新中

全球最火的程序员学习路线!java私塾初级模拟银源代码

经验分享:如何从初级程序员变成高级程序员?

程序媛计划——python初级课时3~5

Java进阶之路——从初级程序员到架构师,从小工到专家(转载)