Jquery+ajax+json+servlet原理和Demo
2014-04-27 16:24
337 查看
Jquery+ajax+json+servlet原理和Demo
大致过程:
用户时间点击,触发js,设置$.ajax,开始请求。服务器响应,获取ajax传递的值,然后处理。以JSON格式返回给ajax。ajax在sucess对应的函数中将返回的json数据进行解析,然后输出到jsp页面。
1.前台index.jsp
[html] view
plaincopy
[html] view
plaincopy
<%@ 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
[java] view
plaincopy
[java] view
plaincopy
/*
* $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;
@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();
}
}
3.配置文件web.xml
[html] view
plaincopy
<?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.js
2.注意乱码的解决方案:
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
未经允许不得用于商业目的
大致过程:
用户时间点击,触发js,设置$.ajax,开始请求。服务器响应,获取ajax传递的值,然后处理。以JSON格式返回给ajax。ajax在sucess对应的函数中将返回的json数据进行解析,然后输出到jsp页面。
1.前台index.jsp
[html] view
plaincopy
[html] view
plaincopy
<%@ 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
[java] view
plaincopy
[java] view
plaincopy
/*
* $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;
@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();
}
}
3.配置文件web.xml
[html] view
plaincopy
<?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.js
2.注意乱码的解决方案:
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
未经允许不得用于商业目的
相关文章推荐
- Jquery+ajax+json+servlet原理和Demo
- Jquery+ajax+json+servlet原理和Demo
- Jquery+ajax+json+servlet原理和Demo
- JQuery、JSON、Ajax在Servlet中的应用
- 【本文完全转载】JSON和JSONP的大概原理,以及jquery中ajax的jsonp、jsonpCallback方法的描述
- servlet+jquery+ajax+json 例子
- jQuery ajax getjson demo
- [原创]jPagerBar1.2发布-jquery分页插件(一个适合Ajax+JSON+jQuery环境使用的多功能页码栏插件)(Demo、源文件下载已更新)
- JQuery、JSON、Ajax在Servlet中的应用
- Jquery通过Ajax发送Json数据到后台验证模拟登陆操作demo
- Ubuntu 14.04 Web 程序开发(4)基于JQuery+Ajax+Json+Servlet实现PUT GET
- 小李飞刀--短平快的AJAX.Jquery+JSON+JAVA.servlet 打造高性价比网站
- Ajax实现下拉框级联(在servlet中把从数据库取出来的值以json形式返回ajax,用jquery遍历便利更新<option>的值)
- EF 4.1+MVC3+Jquery Ajax+Json.Net+JqueryUI+IUnitOfWork+Repository 学习DEMO(暂停更新)
- servlet+jquery+ajax+json 例子
- hibernate中关于servlet+Ajax+jquery+json+gson实现级联效果
- servlet+jquery+ajax+json 例子
- jquery的ajax向后台servlet传递json类型的多维数组
- jquery ajax servlet json(struts2) 动态生成table
- 当使用servlet输出json时,浏览器端jquery的ajax遇到parse error的问题