您的位置:首页 > Web前端 > JQuery

Jquery+ajax+json+servlet原理和Demo

2013-09-01 20:49 471 查看
Jquery+ajax+json+servlet原理和Demo大致过程:用户时间点击,触发js,设置$.ajax,开始请求。服务器响应,获取ajax传递的值,然后处理。以JSON格式返回给ajax。ajax在sucess对应的函数中将返回的json数据进行解析,然后输出到jsp页面。1.前台index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>Jquery Ajax Json Servlet Demo</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript" src="js/jquery.min.js"></script><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)),//发送请求地址timeout:30000,//超时时间:30秒dataType:"json",//设置返回数据的格式//请求成功后的回调函数 data为json格式success:function(data){$("#resultJsonText").text("你的名字:"+data.yourName+"  你输入的内容:"+data.yourContent);},//请求出错的处理error:function(){alert("请求出错");}});}</script></head><body><form id="form1" method="post"><p>评论:</p><p>姓名:<input type="text" name="username" id="username" /></p><p>内容:<textarea name="content" id="content" rows="2" cols="20"></textarea></p><p><input type="button" id="send" value="提交" onclick="jsonAjaxPost()" /></p></form><div class="comment">返回数据:<p id="resultJsonText"></p></div><div id="resText"></div></body></html>
2.后台Servlet
/** $filename: JsonAjaxServlet.java,v $* $Date: Sep 1, 2013  $* Copyright (C) ZhengHaibo, Inc. All rights reserved.* This software is Made by Zhenghaibo.*/package com.njupt.zhb.test;import java.io.IOException;import java.io.PrintWriter;import java.net.URLDecoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/**@author: ZhengHaibo*web:     http://blog.csdn.net/nuptboyzhb *mail:    zhb931706659@126.com*Sep 1, 2013  Nanjing,njupt,China*/public class JsonAjaxServlet extends HttpServlet{/****/private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubdoPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubrequest.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();}}
3.配置文件web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><servlet><servlet-name>jsonAjaxAction</servlet-name><servlet-class>com.njupt.zhb.test.JsonAjaxServlet</servlet-class></servlet><servlet-mapping><servlet-name>jsonAjaxAction</servlet-name><url-pattern>/jsonAjaxAction</url-pattern></servlet-mapping></web-app>
4.其他1.需要导入jquery.min.js2.注意乱码的解决方案: 2.1:js中对字符串进行编码,即:encodeURI(encodeURI(userNameObj)) 2.2:在Servlet中需要用java.net.URLDecoder解码5.结果演示:在浏览器中输入:http://localhost:8080/AjaxServletJson/先输入,然后点击按钮:源代码下载:http://download.csdn.net/detail/nuptboyzhb/6193851参考资料:1.jquery $.ajax参考手册:http://www.w3school.com.cn/jquery/ajax_ajax.asp未经允许不得用于商业目的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: