AJAX+jQuery+JSON



这里只是一个简单的AJAX+jQUery+JSON的例子。


一、页面介绍:一个输入框,一个按钮。点击按钮之后,触发AJAX事件。

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>event click demo</title>

<script src="js/jquery-1.6.4.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
		$("#getUserName").mousedown(function(){
			ajax();
			
		})
	});

	function ajax() {		
		var username = $("#username").val();
		$.ajax({
			type : "post",
			url : "./user.htm?method=getUserName",
			dataType : 'text',
			data : 'username=' + username,
			success : function(data) {
				var json = eval('(' + data+ ')');  //这行对于解析JSON数据很重要,是必须的
				alert("Hello," + json.username)
				alert("music:"+json.music);
			},
		error:function(){
			alert("ERROR HAPPENS");
		}

		});
	}
</script>


</head>
<body>

	<input id="username" type="text" name="username">
	<input id="getUserName" type="button" value="OK">
</body>
</html>



二、后台代码


通过 "./user.htm?method=getUserName",转入到后台。本人用的是Spring的MVC。代码如下:

	public ModelAndView getUserName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		System.out.println("***********Get User Name*******************");
		
		ModelAndView mav = new ModelAndView();
		mav.setViewName("ajaxDemo");
		String userName = request.getParameter("username");
		User user = userService.getUserByName(userName);
		JSONObject result = null;
		if(user != null){
			result = new JSONObject();
			Map<String, String> map = new HashMap<String,String>();
			map.put("userid", String.valueOf(user.getUserId()));
			map.put("username", user.getUserName());
			result = JSONObject.fromObject(map);
			result.put("music", "what are words");
		}
		writeToResponse(response,result);
//		mav.addObject("json", result.toString());
		return mav;

	}

	////此方法用于显示数据
	public void writeToResponse(HttpServletResponse response, JSONObject jsonObj) {
		PrintWriter output = null;
		response.setContentType("text/html;charset=utf-8");
		try {
			output = response.getWriter();
			output.print(jsonObj);
			output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			output.close();
		}
		
		
	}
	



你可能感兴趣的:(jquery,Ajax,json,exception,function,String)