简介
AJAX = Asynchronous JavaScript And XML.
AJAX 并非编程语言。
AJAX 仅仅组合了:
浏览器内建的 XMLHttpRequest 对象(从 web 服务器请求数据)
JavaScript 和 HTML DOM(显示或使用数据)
Ajax 是一个令人误导的名称。Ajax 应用程序可能使用 XML 来传输数据,但将数据作为纯文本或 JSON 文本传输也同样常见。
Ajax 允许通过与场景后面的 Web 服务器交换数据来异步更新网页。这意味着可以更新网页的部分,而不需要重新加载整个页面。
工作流程
![](https://i-blog.csdnimg.cn/blog_migrate/b09cd18b896624e0956138e8dbbea898.png)
案例
通过Ajax实现表单数据同名验证
前端代码:
<script>
function checkName(name) {
var ajax = new XMLHttpRequest();//创建XMLHttpRequest对象
ajax.onreadystatechange = ()=>{//readyState发生变化时,执行onreadystatechange函数
if (ajax.readyState == 4 && ajax.status == 200){
var json= ajax.responseText;
var result = JSON.parse(json);//将json对象转为字符串对象
if (result.code == 0){//根据返回的自定义状态码code判断显示颜色
checkMsg.style.color = "red";
}else {
checkMsg.style.color = "black";
}
checkMsg.innerText = result.msg;
}
}
var url = "/yc123_war_exploded/nameServlet?name="+name;
ajax.open("get",url);
ajax.send();
}
function refreshNames(name) {//显示与输入信息相关数据
var url = "/yc123_war_exploded/nameItemsServlet?name="+name;
get(url,function (result) {//将整个函数作为参数传递给get(url,callback)
names.innerText = "";
var html = "";
for (const n of result.data) {
html += "<option>" + n + "</option>";
}
names.innerHTML = html;
});
}
function get(url,callback) {//回调函数
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = ()=>{
if (ajax.readyState == 4 && ajax.status == 200){
var json= ajax.responseText;
var result = JSON.parse(json);
callback(result);
}
}
ajax.open("get",url);
ajax.send();
}
</script>
<body>
<h3>请在下面的输入框中键入英文姓氏:(已注册的用户名: Abe , Abraham , Acheson)</h3>
<form action="" id="app">
姓氏:
//HTML DOM 事件,onblur 失去焦点后触发该事件 oninput 元素获得用户输入时发生
<input type="text" id="txt1" onblur="checkName(this.value)" oninput="refreshNames(this.value)" list="names"/>
<span id="checkMsg"></span>
<datalist id="names">
<option value="a"></option>
<option value="b"></option>
</datalist>
</form>
</body>
后端部分:
@WebServlet(name = "nameItemsServlet",value = "/nameItemsServlet")
public class nameItemsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");//设置回送数据的字符集编码
String name = request.getParameter("name");//接收前端传送到服务器的参数
List list = new ArrayList();
for (String n:nameServlet.names//遍历nameServlet中的名称数据
) {
if (n.toLowerCase().startsWith(name.toLowerCase())){//转为小写
list.add(n);
}
}
Result result = new Result(1,null,list);
Gson gson = new Gson();
String json = gson.toJson(result);
response.getWriter().printf(json);//回送json对象给浏览器
}
}
@WebServlet(name = "nameServlet" ,value = "/nameServlet")
public class nameServlet extends HttpServlet {
protected static String[] names = {"Abe","Abraham","Acheson","Ackerman(n)","Adam","Adams","Addison","Adela","Adelaide","Adolph","Agnes","Albert","Alcott","Aldington","Aldridge","Aled(k)","Alerander","Alfred","Alice","Alick","Alsop(p)","Aly","Amelia","Anderson","Andrew","Ann","Anna","Anne","Anthony","Antoinette","Antonia","Arabella","Archibald","Armstrong","Arnold","Arthur","Attlee","Augustine","Augustus","Austen","Austin","Babbitt","Bach","Bacon","Baldwin","Barnard","Barney","Barrett","Barrie","Bart","Bartholomew","Bartlett","Barton","Bauer","Beard","Beaufort","Becher","Beck","Becky","Beerbohm","Bell","Bellamy","Belle","Belloc","Ben","Benedict","Benjamin","Bennett","Benson","Bentham","Berkeley","Bernal","Bernard","Bert","Bertha","Bertie","Bertram","Bess","Bessemer","Bessie","Bethune","Betsy","Betty","Bill","Billy","Birrell","Black","Blake","Bloomer","Bloomfield","Bloor","Blume","Bob","Bobby","Boswell","Bowen","Bowman","Boyle","Bradley","Bray","Brewster","Bridges","Bright","Broad","Bronte","Brooke","Brown","Browne","Browning","Bruce","Bruno","Bryan","Bryce","Buck","Buckle","Bulwer","Bunyan","Burke","Burne-Jones","Burns","Butler","Byron","Camilla","Camp","Carey","Carl","Carllyle","Carmen","Carnegie","Caroline","Carpenter","Carrie","Carroll","Carter","Catharine","Cecillia","Chamberlain","Chaplin","Chapman","Charles","Charley","Charlotte","Charles","Chaucer","Chesterton","Child","Childe","Christ","Christian","Christiana","Christie","Christopher","Christy","Church","Churchill","Cissie","Clapham","Clara","Clare","Clarissa","Clark(e)","Clemens","Clement","Cocker","Coffey","Colclough","Coleridge","Collins","Commons","Conan","Congreve","Connie","Connor","Conrad","Constance","Cook(e)","Cooper","Copperfield","Cotton","Coverdale","Cowper","Craigie","Crane","Crichton","Croft","Crofts","Cromwell","Cronin","Cumberland","Curme","Daisy","Dalton","Dan","Daniel","Daniell","Darwin","David","Davy","Defoe","Delia","Den(n)is","DeQuincey","Dewar","Dewey","Dick","Dickens","Dickey","Dillon","Dobbin","Dodd","Doherty","Dolly","Donne","Dora","Doris","Dorothea","Dorothy","Douglas(s)","Doyle","Dierser","Dryden","DuBois","Dulles","Dunbar","Duncan","Dunlop","Dupont","Dutt","Eddie","Eden","Edgeworth","Edie","Edison","Edith","Edmund","Edward","Effie","Eipstein","Eisenhower","Eleanor","Electra","Elinor","Eliot","Elizabeth","Ella","Ellen","Ellis","Elsie","Emerson","Emily","Emma","Emmie","Ernest","Esther","Eugen","Eugene","Euphemia","Eva","Evan","Evans","Eve","Evelina","Eveline","Ezekiel","Fanny","Faraday","Fast","Faulkner","Felix","Felton","Ferdinand","Ferguson","Field","Fielding","Finn","FitzGerald","Flower","Flynn","Ford","Forster","Foster","Fowler","Fox","Frances","Francis","Frank","Franklin","Fred","Frederick","Freeman","Funk","Gabriel","Galbraith","Gallacher","Gallup","Galsworthy","Garcia","Garden","Gard(i)ner","Gaskell","Geoffrey","Geordie","George","Gibbon","Gibson","Gilbert","Giles","Gill","Gissing","Gladstone","Godwin","Gold","Goldsmith","Gosse","Grace","Gracie","Graham","Grant","Grantham","Gray","Green","Gregory","Gresham","Grey","Grote","Gunter","Gunther","Gus","Guy","Habakkuk","Haggai","Hal","Halifax","Hamilton","Hamlet","Hansen","Hansom","Hardy","Harold","Harper","Harriman","Harrington","Harrison","Harrod","Harry","Hart","Harte","Harvey","Hawthorne","Haydn","Haywood","Hazlitt","Hearst","Helin(a)","Hemingway","Henley","Henrietta","Henry","Herbert","Herty","Hewlett","Hicks","Hill","Hobbes","Hobson","Hodge","Hodgson","Holmes","Holt","Hood","Hoover","Hope","Hopkin(s)","Horace","Horatio","Hornby","Hosea","House","Housman","Houston","Howard","Howell(s)","Hoyle","Hubbard","Hudson","Huggins","Hugh","Hughes","Hume","Humphr(e)y","Huntington","Hutt","Huxley","Ingersoll","Irving","Isaac","Isabel","Isaiah","Ivan","Jack","Jackson","Jacob","James","Jane","Jasper","Jeames","Jean","Jefferson","Jenkin(s)","Jennings","Jenny","Jeremiah","Jeremy","Jerome","Jerry","Jessie","Jim","Jimmy","Joan","Job","Joe","Joel","John","Johnny","Johnson","Johnston(e)","Jonah","Jonathan","Jones","Jonson","Jordan","Joseph","Josh","Joshua","Joule","Joyce","Judd","Judith","Judson","Julia","Julian","Juliana","Juliet","Julius","Katte","Katharine","Kathleen","Katrine","Keats","Kell(e)y","Kellogg","Kelsen","Kelvin","Kennan","Kennedy","Keppel","Keynes","Kingsley","Kipling","Kit","Kitto","Kitty","Lamb","Lambert","Lancelot","Landon","Larkin","Lattimore","Laurie","Law","Lawrence","Lawson","Leacock","Lee","Leigh","Leighton","Lena","Leonard","Leopold","Lew","Lewis","Lily","Lincoln","Lindberg(h)","Lindsay","Lizzie","Lloyd","Locke","London","Longfellow","Longman","Lou(ie)","Louis","Louisa","Louise","Lowell","Lucas","Lucia","Lucius","Lucy","Luke","Lyly","Lynch","Lynd","Lytton","MacAdam"};
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");//设置回送数据的字符集编码
String name = request.getParameter("name");
for (String n:names
) {
if (n.equals(name)){
Gson gson = new Gson();
Result result = new Result(0, "该用户已被注册", new int[]{1,2});
String json = gson.toJson(result);
response.getWriter().printf(json);
return;
}
}
String json = "{\"code\":1, \"msg\":\"该用户未被注册\",\"data\":[1,2]}";
response.getWriter().printf(json);
}
}
public class Result {
int code;
String msg;
Object data;
public Result(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public Result() {
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
效果图
输入名称已注册:
![](https://i-blog.csdnimg.cn/blog_migrate/1cae7b2e57b013acf73be57bb78fccef.png)
输入名称未注册:
![](https://i-blog.csdnimg.cn/blog_migrate/fb6b7161de9e214a412b42ac4459f77f.png)
输入首字母可出现提示信息:
![](https://i-blog.csdnimg.cn/blog_migrate/d99016fdea9c40073ac54d4be712c007.png)
![](https://i-blog.csdnimg.cn/blog_migrate/9cc696c27c7e8ad632e00b31aa9e4970.png)