Ajax和jQuery的介绍与使用

零下一度
Lepaskan: 2017-07-19 13:18:13
asal
2185 orang telah melayarinya

认识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/>     用户名:<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>
Salin selepas log masuk

在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);}}
Salin selepas log masuk

2.使用$.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(){   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>
Salin selepas log masuk

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 &#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>");                });
Salin selepas log masuk

//2.下拉框

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>
Salin selepas log masuk

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+"  "+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();}}}
Salin selepas log masuk

 5.在ajax中使用JSON生成主题管理页面

//在上机四中

五.总结部分

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

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

2.Ajax 的关键元素

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

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

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

→CSS:改变样式

→Ajax引擎:即XMLHttpRequest对象

Atas ialah kandungan terperinci Ajax和jQuery的介绍与使用. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan