jsp+ajax+jquery

servlet:

public class JsonAjaxServlet extends HttpServlet {

	/** 
	 *  
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");

		String userName = request.getParameter("userName");
		userName = URLDecoder.decode(userName, "UTF-8");

		String content = request.getParameter("content");
		content = URLDecoder.decode(content, "UTF-8");

		System.out.println("userName:" + userName);
		System.out.println("content:" + content);

		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		// 将数据拼接成JSON格式
		out.print("{\"yourName\":\"" + userName + "\",\"yourContent\":\"" + content + "\"}");
		out.flush();
		out.close();
	}
}
jsp:(只截取javascript部分)

        <script type="text/javascript">  
           function jsonAjaxPost(){  
             var userNameObj=$("#username").val();  
             var contentObj=$("#content").val();  
             $.ajax({  
               type:"post",//请求方式  
               url:"jsonAjaxAction?userName="+encodeURI(encodeURI(userNameObj))  
                   +"&content="+encodeURI(encodeURI(contentObj)),//发送请求地址,encodeURI把中文的请求也转成utf-8格式
               timeout:30000,//超时时间:30秒  
               dataType:"json",//设置返回数据的格式  
               //请求成功后的回调函数 data为json格式  
               success:function(data){  
                  $("#resultJsonText").text("你的名字:"+data.yourName+"  你输入的内容:"+data.yourContent);  
              },  
              //请求出错的处理  
              error:function(){  
                        alert("请求出错");  
              }  
           });  
          }  
    </script> 
mapping:

	<servlet>
		<servlet-name>jsonAjaxAction</servlet-name>
		<servlet-class>liuhuan.JsonAjaxServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>jsonAjaxAction</servlet-name>
		<url-pattern>/we</url-pattern>
	</servlet-mapping>




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值