读书人

JQuery框架跟Ajax的综合使用

发布时间: 2012-08-26 16:48:05 作者: rapoo

JQuery框架和Ajax的综合使用

JQuery是一个优秀的javascript轻量级框架,其口号是:write less,do more,关于该框架的更多内容请参考:http://jquery.org

本实例没有什么具体的意义,但是可以很好的理解如何综合使用JQuery和ajax

在学习该实例前,请确保下载了jquery.js 文件,让后放到你的web工程中(至于怎么放,我就不再多说了,相信有过web开发经验的同学都很清楚)

注意:不同的浏览器运行该实例,可能有不同的效果,最好在ie上面运行

运行界面如下:

JQuery框架跟Ajax的综合使用

对于方式一,我是使用大多JQuery.ajax()函数实现的,对于方式二 我是通过JQuery.get(),JQuery.post()方式完成的。

先将.jsp文件代码拷贝进来:

<script type="text/javascript" src="js/jquery.js"></script><script type="text/javascript">$(document).ready(function(){//当dom加载完成时,就会调用ready方法,在此时,为四个按钮分别添加onclick方法$("#btn1").click(function(){ $.ajax({ type:"GET",//注意: 此处使用的get方法发送的 url:"MyServlet", dataType:"html", success:function(data)//相当于之前文章讲解的ajax中的回调函数,就是说如果请求成功,那么就会执行该函数,其中dada便是从服务器发送回来的数据 { alert(data);  $("#div1").html(data);//jquery语法,找到id为div1的标签,然后放data放入到标签中 } });  });$("#btn2").click(function(){$.ajax({type:"POST",//通过post方法发送url:"MyServlet",dataType:"html",///返回类型是htmlsuccess:function(data){//alert(data);$("#div1").html("");$("#div1").html(data);}});});$("#btn3").click(function(){$.get("MyServlet",function(data){alert(data);$("#div1").html(data);});});$("#btn4").click(function(){$.post("MyServlet",function(data){$("#div1").html(data);//});});});</script>  </head>    <body>  <p>方式一</p>   <input type="button" id="btn1" value="使用Get方法获取服务器端的内容"><br>   <input type="button" id="btn2" value="使用Post方法获取服务器内容"> <br>   <hr>   <p>方式二</p>     <input type="button" id="btn3" value="使用Get方法获取服务器端的内容"><br>     <input type="button" id="btn4" value="使用Post方法获取服务器内容"> <br>         <div id="div1"></div>   <hr>     </body>


上面的代码都有注释,在此就不多做解释,不懂的地方可以留言

下面就开始编写servlet代码

public class MyServlet extends HttpServlet{/** * Destruction of the servlet. <br> */public void destroy(){super.destroy(); // Just puts "destroy" string in log// Put your code here}public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("Hello world");out.flush();out.close();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{System.out.println("post方法执行了");response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("Good Morning");out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException{// Put your code here}}


servlet代码比较简单,无非就是改写了get方法,post方法

读书人网 >Ajax

热点推荐