ajax
overview
Ajax refers to a technology for creating interactive web applications and development.
Ajax is a technology for creating fast and dynamic web pages, which
can make web pages update asynchronously, which means that a certain part of a web page can be updated without reloading the entire web page. update
application
step
Create an asynchronous request object
, open the connection
, send the request,
set the function triggered by the change of the listening object, and process the result
js-ajax
Getting started with the get request method
<body>
<input type="button" value="跳转get" onclick="ajaxDemo()">
</body>
<script>
function ajaxDemo(){
var xmlHttp = null;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("GET","../servletDemo?username = zs")
xmlHttp.send();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var result = xmlHttp.responseText;
alert(result);
}
};
}
</script>
Getting started with the post request method
<body>
<input type="button" value="跳转post" onclick="ajaxdemo2">
</body>
<script>
function ajaxdemo2() {
var xmlHttp = null;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("POST","../servletDemo")
xmlHttp.setRequestHeader("content-type","application/x-www-form-urlencoded");
xmlHttp.send("username=zs&&password=123456");
xmlHttp.onreadystatechange = function () {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var result = xmlHttp.responseText;
alert(result);
}
};
}
</script>
Object XMLHttpRequest for asynchronous requests
Different browsers create this object in different ways. When earlier browsers created this object, they encapsulated this object into the ActiveXObject plug-in, and new browsers directly created it.
<script>
function createXmlHttp() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml12.XMLHTTP");
}
catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
}
}
}
return xmlHttp;
}
</script>
API
open(): Open the connection. Pass three parameters. The first is the request method (get/post), the second is the request path, and the third is whether it is asynchronous (the default is asynchronous, so generally there is no need to specify it) send([post request parameters]):
send Request
setRequestHeader(): Solve the problem of post request parameters, key and value content-type
Attribute
onreadystatechange: To monitor the state change of the object, a function is required to correspond to it
readyState: This attribute records the state of the object
0 | The object has been created, but not yet initialized, and the open method has not been called |
---|---|
1 | The object has been created and the send method has not been called |
2 | The send method has been called, but the current status and http headers are unknown |
3 | Part of the data has been received, because the response and http headers are incomplete, and an error will occur when obtaining part of the data through responseBody and responseText |
4 | After the data is received, complete data can be obtained through responseBody and responseText |
status: status code
responseText: get the response data in string form (response body)
responseXML: get the response data in XML form (response body)
Use js to realize asynchronous verification of user name
page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<center>
<h1>用户注册页面</h1>
<table border="1px" width="500px">
<tr>
<td>用户名:</td>
<td><input type="text" id="username" onblur="checkUserName(this)" />
<span id="usernamespan"></span>
</td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" />
</td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="password" />
</td>
</tr>
<tr>
<td>电话:</td>
<td><input type="password" />
</td>
</tr>
<tr>
<td><input id="submitId" type="button" value="注册"/></td>
</tr>
</table>
</center>
</body>
<script>
function checkUserName(obj) {
var username = obj.value;
var xmlHttp = null;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("get","../userServlet?username = " + username);
xmlHttp.send();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
var flag = xmlHttp.responseText;
if(flag){
document.getElementById("usernamespan").innerHTML = "<font color='green'>用户名可用</font>";
}
else {
document.getElementById("usernamespan").innerHTML = "<font color='red'>用户名已经被占用</font>";
}
}
}
}
</script>
</html>
bean
package bean;
public class User {
private int id;
private String username;
private String password;
private String email;
private String phone;
public User() {
}
public User(int id, String username, String password, String email, String phone) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", phone='" + phone + '\'' +
'}';
}
}
dao
public User findByUserName(String username){
try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(C3p0Utils.getDataSource());
String sql = "select * from user where username = ?";
User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), username);
return user;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
service
public boolean checkUserName(String username){
UserDao userDao = new UserDao();
User user = userDao.findByUserName(username);
if (user != null){
return true;
}
else
return false;
}
web
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
UserService userService = new UserService();
boolean isExit = userService.checkUserName(username);
if (isExit){
response.getWriter().print(true);
}
else{
response.getWriter().print(false);
}
}
}
jq ajax
API
request method | grammar |
---|---|
GET request | $.get(url,[data],[callback],[type]) |
POST request | $.post(url,[data],[callback],[type]) |
AJAX request | $.ajax([settings]) |
GET request | $.get([settings]) |
POST request | $.post([settings]) |
application
get()
$.get(url,[data],[callback],[type])
parameter name | explain |
---|---|
url | The requested server-side url address |
data | The request parameter sent to the server, the format can be key = value, or a js object |
callback | When the callback function after the request is successful, we can write our logic code in the function body |
type | The expected return data type, the value can be xml, html, script, json, text, _default, etc. |
<script>
//发送请求:$.get(url,[params],[function(result){}])
$.get("{pageContext.request.contextPath}/demo01",{
"username":"zs","password":"123456"},function (result) {
alert(result);
})
</script>
post()
$.post(url,[data],[callback],[type])
<script>
//发送请求:$.post(url,[params],[function(result){}])
$.post("{pageContext.request.contextPath}/demo01",{
"username":"zs","password":"123456"},function (result) {
alert(result);
})
</script>
ajax()
$.ajax([settings])
settings is an object in the form of a js literal.
The format is {name:value,name:value... ...} The
commonly used name attribute names are as follows
attribute name | explain |
---|---|
url | The requested server-side url address |
async | By default, all requests are asynchronous. If you need to send synchronous information, set it to false |
data | The data sent to the server can be in the form of key-value pairs or js objects |
type | (default: "GET") request method ("POST" or "GET", default is "GET") |
datatType | The expected return data type, the value can be xml, html, script, json, text, _default, etc. |
success | Callback function after successful request |
error | Function to call when request fails |
<script>
function sendRequest() {
$.ajax({
url: "/AjaxDemo/ajaxServlet",
async: true,
data: "name = haohao&age = 33",
type: "GET",
dataType: ("text"),
success: function () {
alert("数据没有成功返回")
}
});
}
</script>
new features
$.get({
url:"../servletDemo01",
async:true,
data:"name = haohao$ age = 13",
type:"GET",
dataType:"text",
success:function () {
alert("...")
}
})
$.post({
url:"../servletDemo01",
async:true,
data:"name = haohao$ age = 13",
type:"GET",
dataType:"text",
success:function () {
alert("...")
}
error:functiong(){
alert("...")
}
})
the case
<script>
$("#username").blur(function () {
var usernameValue = this.value;
$.post("../userServlet",{
username:usernameValue},function (result) {
if(result){
$("#usernamespan").html = "<font color='green'>用户名可用</font>";
}
else {
$("#usernamespan").html = "<font color='red'>用户名已经被占用</font>";
}
})
})
</script>
JSON
JSON is a data format that is easy to generate and parse
Data Format
type | grammar | explain |
---|---|---|
JSON object | {name:value,name:value…} | name is a string type, value is any type |
JSON array | [value,value,value] | Where value is any type |
mixed type | [{},{}……] or {key:[]……} | Reasonable wrapping of nested object types and array classes |
The json conversion tool
is some jar toolkit packaged by java, which directly converts java objects or collections into strings in json format