jquery访问servlet并返回数据到页面的方法
本文实例讲述了jquery访问servlet并返回数据到页面的方法。分享给大家供大家参考。具体实现方法如下:
1. servlet:ajaxservlet.java如下:
import java.io.ioexception;
import java.io.printwriter;
import java.net.urldecoder;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
public class ajaxservlet extends httpservlet {
private static final long serialversionuid = 1l;
protected void doget(httpservletrequest req, httpservletresponse resp)
throws servletexception, ioexception {
integer total = (integer) req.getsession().getattribute("total");
int temp = 0;
if(total == null ){
temp = 1;
}else{
temp = total.intvalue() + 1;
}
req.getsession().setattribute("total",temp);
try {
//1.取参数
resp.setcontenttype("text/html;charset=gbk");
printwriter out = resp.getwriter();
string old = req.getparameter("name");
//2.检查参数是否有问题
//string name = new string(old.getbytes("iso8859-1"),"utf-8");
string name = urldecoder.decode(old,"utf-8");
if("".equals(old) || old == null){
out.println("用户名必须输入");
}else{
if("liling".equals(name)){
out.println("恭喜登录成功");
return;
}else{
out.println("该用户名未注册,您可以注册["+name+"]这个用户名"+temp);
}
}
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
//3.检验操作
}
protected void dopost(httpservletrequest req, httpservletresponse resp)
throws servletexception, ioexception {
doget(req, resp);
}
}
2. verify.js如下:
//解决中文乱码问题的方法1,页面端发出的数据作一次encodeuri,服务端使用new string(old.getbytes("iso8859-1"),"utf-8");
//解决中文乱码问题的方法2,页面端发出的数据作两次encodeuri,服务端使用string name = urldecoder.decode(old,"utf-8");
var url = "servlet/ajaxservlet?name="+encodeuri(encodeuri($("#username").val()));
url = converturl(url);
$.get(url,null,function(data){
$("#result").html(data);
});
}
//给url地址增加时间蒫,难过浏览器,不读取缓存
function converturl(url){
//获取时间戳
var timstamp = (new date()).valueof();
//将时间戳信息拼接到url上
if(url.indexof("?") >=0){
url = url + "&t=" + timstamp;
}else{
url = url + "?t=" + timstamp;
}
return url;
}
3. 前台页面如下:
<html>
<head>
<title>ajax实例</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=gbk">
<script type="text/javascript" src="js/verify.js"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
<font color="blue" size="2">请输入用户名:</font>
<input type="text" id="username" /><font color="red" size="2"><span id="result" >*</span></font><br/><br/>
<!-- <div id="result"></div> -->
<input type="submit" name="提交" value="提交" onclick="verify()"/>
</body>
</html>
希望本文所述对大家的ajax程序设计有所帮助。
上一篇: vue中用H5实现文件上传的方法实例代码