javaweb总结(九)--从jsp页面发送ajax请求,servlet接受参数并返回json数据

来自:https://blog.csdn.net/yanghan1222/article/details/78447231

今天遇到了问题把我难住了,解决之后就赶紧来记下来

这是一个很简单的更新用户的问题

先来看看项目所需jar包

接下来就是jsp页面的东西,ajax发送id

function editCustomer(id) {
			$.ajax({
				type:"get",
				url:"${pageContext.request.contextPath }/editStudioServlet",
				data:{"id":id}, 
				success:function(data) {
					$("#edit_cust_id").val(${data.cust_id});
					$("#edit_customerName").val(data.cust_name);
					$("#edit_phone").val(data.cust_phone);
					$("#edit_mobile").val(data.cust_mobile); 
					alert(data);
					
				}
			});
		}

然后在servlet接受参数,并去数据库查询结果

String id = request.getParameter("id");
		//System.out.println(id);
		StudioDao dao = new StudioDaoImpl();
		Customer studio = null;
		try {
			studio = dao.getCustomerById(Integer.parseInt(id));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Gson gson = new Gson();
		String json = gson.toJson(studio);
		response.setCharacterEncoding("UTF-8");  
		response.setContentType("application/json; charset=utf-8");  
		PrintWriter writer = response.getWriter();
		writer.append(json);

然后Ajax的回调函数将从servlet发送过来的json数据填入input框中完成。

最后贴一张图

扫描二维码关注公众号,回复: 4402466 查看本文章

猜你喜欢

转载自blog.csdn.net/lsx2017/article/details/84845796