我是靠谱客的博主 秀丽麦片,这篇文章主要介绍ajax 与 servlet的应用,现在分享给大家,希望可以做个参考。

以检测用户名是否存在为例:

首先创建jsp页面;代码如下

复制代码
1
2
3
4
5
6
<body> 用户名:<input type="text" id="username"/><br> <div id="checkdiv"> </div> <input type="button" id="button" value="按钮" οnclick="check()"/> </body>

然后编写javasc页面:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<script type="text/javascript"> var xmlhttp; //获取 function createXmlHttp() { //根据window.XMLHttpRequest对象是否存在使用不同的创建方式 if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); //FireFox、Opera等浏览器支持的创建方式 } else { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器支持的创建方式 } } function check(){ var name = document.getElementById("username").value; createXmlHttp(); //创建XmlHttpRequest对象 xmlHttp.onreadystatechange = checkName; xmlHttp.open("GET", "test?username=" + name, true); xmlHttp.send(null); } function checkName(){ if (xmlHttp.readyState == 4) { var value = xmlHttp.responseText; //取得地区信息 //当地区信息包含数据时将信息写回到文本框中 document.getElementById("checkdiv").innerHTML=value; } } </script>

创建AJAX可以使用这样的步骤:

1、创建全局变量xmlHttp;

2、编写初始化方法createXmlHttp(),什么时候需要用到xmlHttp,直接createXmlHttp();

3、调用onreadystatechange方法;

4、编写收到servlet传来值的方法;

Servlet按照正常创建即可

如有乱码问题可以再servlet中补充这样的代码:

response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("utf-8");

test文件的内容为:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
public void doGet(HttpServletRequest request, HttpServletResponse response)             throws ServletException, IOException {           response.setContentType("text/html;charset=UTF-8");         request.setCharacterEncoding("utf-8");         PrintWriter out = response.getWriter();         String name = request.getParameter("username");         if(name.equals("wxc")){             out.println("用户名已存在");         }else{             out.println("用户可以使用");         }     }


 

 

最后

以上就是秀丽麦片最近收集整理的关于ajax 与 servlet的应用的全部内容,更多相关ajax内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部