ajax
支持异步请求,支持页面的局部刷新
JS原生ajxa
核心对象:XMLHttpRequest 对象
<script
>
onload = function() {
document
.getElementById("btn1").onclick = function () {
var request
= new XMLHttpRequest();
request
.onreadystatechange = function () {
if (request
.readyState
== 4 && request
.status
== 200) {
document
.getElementById("myDiv").innerHTML
= request
.responseText
;
}
}
request
.open("GET", "/web_war_exploded/DemoServlet", true);
request
.send();
}
}
</script
>
<body>
<button id="btn1">使用JS发送ajax异步请求
</button>
<br/>
<div id="myDiv"></div>
</body>
JQuery发送ajax请求
$.get() — 只能发送异步请求,默认字符集:utf-8
$("#btn1").click(function () {
$
.get("/web_war_exploded/DemoServlet",
"id=1&name=张三",
function(response
) {
console
.log("响应回来的数据是: " + response
);
$("#myDiv").html(response
);
},
"text"
);
});
$.post() — 只能发送异步请求,默认字符集:utf-8
$("#btn2").click(function () {
$
.post("/web_war_exploded/DemoServlet",
{
id
: 1,
name
: $("#input").val()
},
function(response
) {
$("#myDiv").html(response
);
},
"text"
);
});
$.ajax() — 同步/异步
$("#btn3").click(function () {
$
.ajax({
url
: "/web_war_exploded/DemoServlet",
data
: {
id
: 1,
name
: $("#input").val()
},
success
: function(data
) {
$("#myDiv").html(data
.name
+ ", " + data
.age
);
},
dataType
: "json",
type
: "GET",
async: false
});
});
String id
= request
.getParameter("id");
String name
= request
.getParameter("name");
String json
= "{ \"name\": \""+ name
+"\", \"age\": "+ id
+" }";
response
.setContentType("application/json;charset=utf-8");
response
.getWriter().write(json
);
注册案例:判断用户名是否存在
$("#username").blur(function() {
$
.get("/web_war_exploded/CheckUserServlet",
{username
: this.value
},
function(data
) {
if(data
.flag
){
$("#usernameError").html("用户名已存在");
} else {
$("#usernameError").html("用户名可用");
}
},
"json"
);
});
String username
= request
.getParameter("username");
UserService us
= new UserServiceImpl();
boolean isExists
= us
.checkUser(username
);
ResponseInfo info
= new ResponseInfo();
info
.setFlag(isExists
);
response
.setContentType("application/json;charset=utf-8");
ObjectMapper mapper
= new ObjectMapper();
mapper
.writeValue(response
.getOutputStream(), info
);
@Override
public boolean checkUser(String username
) {
UserDao ud
= new UserDaoImpl();
User user
= ud
.findUserByUsername(username
);
if (user
!= null
) {
return true;
}
return false;
}
private JdbcTemplate jdbcTemplate
= new JdbcTemplate(DruidUtils
.getDataSource());
@Override
public User
findUserByUsername(String username
) {
String sql
= "select * from user where name = ?";
List
<User> list
= jdbcTemplate
.query(sql
, new BeanPropertyRowMapper<>(User
.class), username
);
return list
.size() == 0 ? null
:list
.get(0);
}