Home  >  Article  >  Web Front-end  >  Introduction and use of Ajax and jQuery

Introduction and use of Ajax and jQuery

零下一度
零下一度Original
2017-07-19 13:18:132202browse

Understand ajax, XMLHttpRequest, use jquery to implement ajax, process response data in json format, and use native JavaScript to implement ajax

1. Miscellaneous Notes

1. Traditional web technology and The request method of ajax is different. Ajax only gets the required elements. Traditional refresh all

2. The full name of ajax is "Asynchronous Javascript And XML" (Asynchronous JavaScript and XML)

3. The work of ajax The process user interface sends an http request to ajax through JavaScript --- the server (processes the request)

and then returns the xml/json/html data to the ajax engine and then returns to the user interface through dom+css

4.XMLHttpRequest provides the ability to send requests asynchronously

Common methods

open(String method,String url,boolean async) creates a new HTTP request,

send(String data ) Send a request to the server,

setRequestHeader(String header,String value) sets a certain HTTP header information of the request,

5. The old version of IE browser and the new version are most The creation of XMLHttpRequest by browsers is different

6. Event onreadystatechange: callback function

2. Hands-on part

1. Implement the check to see if the registered user’s mailbox exists (use the original Ecological JavaScript implements ajax)

<div style="left: 2200px;"><form action="" method="get">    注册邮箱:<input type="text" id="email" onblur="checkemail()" ><label id="samp">*</label><br/><br/>     用户名:<input type="text">*<br/><br/>      密码:<input type="password">*<br/><br/>    确认密码:<input type="password">*<br/><br/>    <div style="margin-left: 100px;"><input type="submit" value="注册"></div>
</form> <script type="text/javascript" language="JavaScript">        function checkemail() {        //alert("hnjkl");            //创建XMLHttpRequest对象            if(window.XMLHttpRequest){//返回true时说明是新版本IE浏览器或其他浏览器                xmlHttpRequest=new XMLHttpRequest();            }else{//返回false时说明是老版本IE浏览器                xmlHttpRequest=new XMLHttpRequest("Microsoft.XMLHTTP");            }//设置回调函数            xmlHttpRequest.onreadystatechange=callBack;//获取用户名文本框的值            var email=$("#email").val();//初始化XMLHttpRequest组件            var url="userServlet?email="+email;//服务器端URL地址,name为用户名文本框的值            xmlHttpRequest.open("GET",url,true);//发送请求            xmlHttpRequest.send(null);//回调函数callBack()中处理服务器响应的关键代码            function callBack(){                if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){                    var date=xmlHttpRequest.responseText;                    if(date=="true"){                        $("#samp").html("邮箱已被占用");//samp为显示消息的samp的id                    }else{                        $("#samp").html("邮箱可注册");                    }                }            }        }
</script></div>

The code in the servlet is as follows

package web;
import java.io.IOException;import java.io.PrintWriter;
import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
public class userServlet extends HttpServlet{
@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubrequest.setCharacterEncoding("UTF-8");boolean emailCheck=false;String email=request.getParameter("email");if("22@qq.com".equals(email)){emailCheck=true;}else {emailCheck=false;}response.setContentType("text/html;charset=UTF-8");PrintWriter out=response.getWriter();out.print(emailCheck);out.flush();out.close();}
@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubrequest.setCharacterEncoding("UTF-8");this.doGet(request, response);}}

2. Use the $.ajax() method to asynchronously check whether the registered email address already exists

<div style="left: 2200px;"><form action="" method="get">    注册邮箱:<input type="text" id="email" onblur="checkemail()" ><label id="samp">*</label><br/><br/>     用户名:<input type="text">*<br/><br/>      密码:<input type="password">*<br/><br/>    确认密码:<input type="password">*<br/><br/>    <div style="margin-left: 100px;"><input type="submit" value="注册"></div>
</form>  <script type="text/javascript" language="JavaScript">  function checkemail(){   var email=$("#email").val();    $.ajax({        "url"  :"userServlet",        "type" :"get",        "data"  :"email="+email,        "dataType" :"text",        "success"  :callBack,        "error" :function () {            alert("出现错误");        }    });    function callBack(data) {        if(data=="true"){            $("#samp").html("邮箱已被占用");//samp为显示消息的samp的id        }else{            $("#samp").html("邮箱可注册");        }    }  }    </script></div>

3. Display JSON data with common page elements

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP &#39;workthree.jsp&#39; starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css?1.1.11">--><script type="text/javascript" src="js/jquery-1.8.3.js?1.1.11"></script>   <script type="text/javascript">        $(document).ready(function(){        var personary=["大东-河南省周口13838381438市-","小顺-广东省xx市"];            var person=[{"id":"1001","name":"大东","address":"河南省周口市","phone":"13838381438"},                {"id":"1002","name":"小圳","address":"湖南省xx市","phone":"13838381438"},                {"id":"1003","name":"小顺","address":"广东省xx市","phone":"13838381438"},                {"id":"1004","name":"小莫","address":"河北省xx市","phone":"13838381438"}];                var $divv=$("#con");            var $table=$(" <table border=&#39;1&#39; ></table>").append("<tr><td>ID</td><td>姓名</td><td>住址</td><td>手机</td></tr>");             $divv.append($table);                $(person).each(function(){                $table.append("<tr><td>"+this.id+"</td><td>"                +this.name+"</td><td>"                +this.address+"</td><td>"                +this.phone+"</td></tr>");                });

//2. Drop-down box

var $ary=$(personary);//var $ul=$("#arul");var $sel=$("#arse");$ary.each(function(i) {                    $sel.append("<option value=&#39;"+(i+1)+"&#39;>"+this+"</option>");                });        });    </script>  </head>  <body>
<div id="con">
</div><div id="conn"><select id="arse"></select></div>  </body></html>

4. Use JSON generation in ajax Administrator News Management Page

//This page will not be uploaded. If you need the complete project code, you can find it in Sogou Search (accp8.0 conversion textbook Chapter X) on csdn and download it

//The most important thing is js

/** * Created by Administrator on 2017/7/4. */$(function(){ $.ajax({"url":"userServlet2","type":"POST","data":"por=user","dataType":"json","success":callBack}); $("#news").click(function(){ initnews(); }); $("#topics").click(function(){ inittopics(); });});
function callBack(data){var $data=$(data);var $userul=$("#userul");$data.each(function(){$userul.append("<li>"+this.naem+"  "+this.pwd+"  <a href=&#39;&#39;>修改</a>  <a href=&#39;&#39;>删除</a></li>");});}function initnews(){$.ajax({        "url":"userServlet2",        "type":"POST",        "data":"por=news",        "dataType":"json",        "success":callNews    });function callNews(news){//alert("ddd");var $userul=$("#userul").empty();for(var i=0;i<news.length;){$userul.append("<li>"+news[i].title+"            "+news[i].author+"  <a href=&#39;&#39;>修改</a>  <a href=&#39;&#39;>删除</a></li>");i++;if(i==news.length){break;}}}}function inittopics(){$.ajax({        "url":"userServlet2",        "type":"POST",        "data":"por=top",        "dataType":"json",        "success":callTopics    });function callTopics(top){var $userul=$("#userul").empty();for(var i=0;i<top.length;){//alert("ddd");$userul.append("<li>"+top[i].topics+"  <a href=&#39;&#39;>修改</a>  <a href=&#39;&#39;>删除</a></li>");i++;        if(i==top.length){break;}}}}
//servlet代码
package web;
import java.io.IOException;import java.io.PrintWriter;import java.util.List;
import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import dao.newlist;import dao.topdao;import daoImpl.newlistimpl;import daoImpl.topimpl;import entity.news;import entity.top;
public class userServlet2 extends HttpServlet{
@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stub//doPost(request, response);}
@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");String por=request.getParameter("por");if(por.equals("news")){newlist nd=new newlistimpl();List<news> listnews=nd.allnewslist();StringBuffer newssub=new StringBuffer("[");for(int i=0;;){news n=listnews.get(i);newssub.append("{\"title\":\""+n.getNtitle()+"\",\"author\":\""+n.getAuthour()+"\"}");i++;if(i==listnews.size()){break;}else{newssub.append(",");}}newssub.append("]");response.setContentType("text/html;charset=UTF-8");PrintWriter out=response.getWriter();out.print(newssub);out.flush();out.close();}else if(por.equals("top")){topdao nd=new topimpl();List<top> listtop=nd.alltop();StringBuffer topsub=new StringBuffer("[");for(int i=0;;){top top=listtop.get(i);topsub.append("{\"topics\":\""+top.getTcontent()+"\"}");i++;if(i==listtop.size()){break;}else{topsub.append(",");}}topsub.append("]");response.setContentType("text/html;charset=UTF-8");PrintWriter out=response.getWriter();out.print(topsub);out.flush();out.close();}}}

5. Use JSON in ajax to generate the theme management page

//On the computer four

5. Summary part

1. Traditional web development technology sends requests through the browser and ajax sends through JavaScript’s xmlhttprequest object

The traditional response is a complete page and JavaScript returns the required data

2. Key elements of Ajax

→JavaScript language: the main development language of Ajax technology

→XML/JSON/HTML: used to encapsulate data

→DOM (document Object model): Modify page elements

→CSS: Change style

→Ajax engine: XMLHttpRequest object

The above is the detailed content of Introduction and use of Ajax and jQuery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn