1. 程式人生 > >javaweb總結(九)--從jsp頁面傳送ajax請求,servlet接受引數並返回json資料

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框中完成。

 

最後貼一張圖