欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

Ajax和jQuery的介绍与使用

程序员文章站 2022-03-06 12:07:03
...
认识ajax 、XMLHttpRequest、使用jquery实现ajax、处理json格式的响应数据、使用原生态JavaScript实现ajax

一.杂记

1.传统web技术和ajax的请求方式不同 ajax是只获得需要的元素 传统刷新全部

2.ajax的全称是“Asynchronous Javascript And XML”(异步JavaScript和XML)

3.ajax的工作流程 用户界面通过JavaScript到ajax发送http请求---服务器(处理请求)

再返回xml/json/html数据到ajax引擎再由dom+css返回到用户界面

4.XMLHttpRequest提供异步发送请求能力

常用方法

open(String method,String url,boolean async)创建一个新的HTTP请求、

send(String data) 发送请求到服务器端、

setRequestHeader(String header,String value)设置请求的某个HTTP头信息、

5.老版本的IE浏览器和新版的即大部分浏览器的创建XMLHttpRequest不一样

6.事件onreadystatechange:回调函数

二.上机部分

1.实现检查注册用户的邮箱是否存在(使用原生态JavaScript实现ajax)

<div style="left: 2200px;"><form action="" method="get">    注册邮箱:<input type="text" id="email" onblur="checkemail()" ><label id="samp">*</label><br/><br/>    &nbsp;用户名:<input type="text">*<br/><br/>    &nbsp;&nbsp;密码:<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>

在servlet中代码如下

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.使用$.ajax()方法实现异步检查注册邮箱是否已存在

<div style="left: 2200px;"><form action="" method="get">    注册邮箱:<input type="text" id="email" onblur="checkemail()" ><label id="samp">*</label><br/><br/>    &nbsp;用户名:<input type="text">*<br/><br/>    &nbsp;&nbsp;密码:<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.以常见页面元素展示JSON数据

<%@ 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 'workthree.jsp' 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='1' ></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.下拉框

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

4.在ajax中使用JSON生成管理员新闻管理页面

//在这里页面就不上传了如有需要完整项目代码在csdn能找到 搜狗搜索 (accp8.0转换教材第X章)就能下载

//最主要的是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+"&nbsp;&nbsp;"+this.pwd+"&nbsp;&nbsp;<a href=''>修改</a>&nbsp;&nbsp;<a href=''>删除</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+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+news[i].author+"&nbsp;&nbsp;<a href=''>修改</a>&nbsp;&nbsp;<a href=''>删除</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+"&nbsp;&nbsp;<a href=''>修改</a>&nbsp;&nbsp;<a href=''>删除</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.在ajax中使用JSON生成主题管理页面

//在上机四中

五.总结部分

1.传统的web开发技术通过浏览器发送请求 而ajax通过JavaScript的xmlhttprequest对象发送

传统的响应的是一个完整页面 而JavaScript返回需要的数据

2.Ajax 的关键元素

→JavaScript语言:Ajax技术的主要开发语言

→XML/JSON/HTML:用来封装数据

→DOM(文档对象模型):修改页面元素

→CSS:改变样式

→Ajax引擎:即XMLHttpRequest对象

以上就是Ajax和jQuery的介绍与使用的详细内容,更多请关注其它相关文章!