几个月前,写了一遍记录 js调用后台方法的博客,地址为:http://blog.csdn.net/duanml61/article/details/7912933
一些同学看到之后,发现还是无法满足需求,为此,这篇详解js和后台之间的参数传递问题
第一步:新建一个html页面,引入jquery-1.7.min.js,其他的版本未测试,应该差不多
<!DOCTYPE html>
<html>
<head>
<title>portrait</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script language="javascript" src="jquery-1.7.min.js"
type="text/javascript"></script>
</head>
<body>
</body>
</html>
第二步:新建servlet,doGet()或doPost()方法中执行相关后台操作,得到返回值
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String userPortrait = portraitHandle.queryPortraitSet(request
.getParameter("jid"));
out.print(userPortrait);
}
out.print(userPortrait);这句将后台得到的userPortrait参数传到js回调函数中
第三步:写ajax方法
function initUserPortrait() {
$.ajax({
type : "POST",
async : false,
contentType : "application/json",
url : "PortraitServlet",
dataType : 'text',
success : function(data) {
document.getElementById("portrait").src = data;
}
});
}
很短很简单……完
p.s.这篇应该2012最后一篇博客了,但愿新的2013年能够幸运些,找到一份好工作~~
dml@2012.12.28