什么是Ajax
Ajax 及英文名为 Asynchronous JavaScript And XML 顾名思义,异步的JavaScript和XML,他是现代网络交前后台交互中一种非常重要的一种异步交互技术。
Ajax是一种在无需加载整个网页的情况下,能够更新部分网页的技术。
同步和异步概念图
为什么需要ajax
传统的网页(不适用)Ajax如果需要更新内容,必须重载整个网页页面。比较浪费网络资源,且用户体验较差,为了改进这些缺点,ajax基础便由此而生
使用Ajax可节省网络资源,提升用户体验。
如何使用ajax
ajax实现方式
原生方式写ajax
浏览器端:
function fun() {
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//startup connection
/***
* 参数:
* 1.请求方式,get、post
* get方式,请求参数在URL后面拼接,send方法为空参
* post方式, 请求参数在send方法中定义
* 请求url
* 同步或者异步请求,true(异步)或false(同步)
***/
xmlhttp.open("GET","ajaxServlet?username=tom",true);
//xmlhttp.send("username=tom");
xmlhttp.send();
//数据处理
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
alert(responseText);
}
}
}
服务端:
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
System.out.println(username);
response.getWriter().write("hello:"+username);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
jquery方式写ajax
$.ajax()
语法:$.ajax({键值对});
function fun() {
$.ajax({
url:"ajaxServlet",
type: "post",
//第一种数据请求方式
//: data:"username=jack&age=23",
//第二种数据请求方式
data:{
"username":"jack","age":23},
success:function (data) {
alert(data);
},
error:function () {
alert("error......")
},
dataType: "text"
});
}
- . g e t ( ) 语 法 : .get() 语法: .get()语法:.get(url, [data], [callback], [type])
参数:
url:请求路径
data:请求参数
callback:回调函数
type:响应结果的类型
function fun() {
$.get("ajaxServlet",{
username:"rose"},function (data) {
alert(data);
},"text");
}
- $.post()
与上述get是一致的
function fun() {
$.post("ajaxServlet",{
username:"rose"},function (data) {
alert(data);
},"text");
}