前后端交互( Ajax and JSON)
Ajax and JSON
Ajax
(一)、概念
百度百科: Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
(二)、实现方式
(一)、原生JS实现
客户端
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function fun(){ var xmlhttp; if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest;
}else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } /*** *参数: 1、请求方式:GET POST * get方式,请求参数在URL后边进行拼接,send方法为空参 * post方式,请求参数在send方法中定义 2、请求的URL 3、同步或异步请求:true(异步)或 false(同步) **/ xmlhttp.open("GET","ajaxServlet?name=hello",true); xmlhttp.send();
} </script> </head> <body> <input type="button" value="" onclick="fun()"> </body> </html>
|
服务器端
1 2 3 4 5 6 7 8 9
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uname = request.getParameter("name"); System.out.println(uname); response.getWriter().write("hello:"+uname); }
|
(二)、Jquery实现
1、$.ajax()方法实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <script> function fun(){ $.ajax({ url: "ajaxServlet",
type: "get",
data: {"name":"Tom"},
success: function(data){ alert(data); }, errore: function(){ alert("请求出现错误!"); }, dataType: "text" }); } </script>
|
2、$.get() an $.post()方法实现
$.get()方法处理get请求,$.post()方法处理post请求,它们的语法是格式是一样的。
1 2 3 4 5 6 7 8 9
| 语法:
$.get(url,[data],[callback],[type]) $.post(url,[data],[callback],[type])
|
1 2 3 4 5 6 7 8 9 10
| function fun(){ $.get("ajaxServlet",{name:"Tom"},function(data){ alert(data); },"text"); } function fun(){ $.post("ajaxServlet",{name:"Tom"},function(data){ alert(data); },"text"); }
|