首頁 > web前端 > js教程 > Ajax與jQuery的介紹與使用

Ajax與jQuery的介紹與使用

零下一度
發布: 2017-07-19 13:18:13
原創
2237 人瀏覽過

認識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>
登入後複製

在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/>     用户名:<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.以常見頁面元素展示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>");                });
登入後複製

//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>
登入後複製

 

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();}}}
登入後複製

 5.在ajax中使用JSON產生主題管理頁面

//在上機四

五.總結部分

1.傳統的web開發技術透過瀏覽器發送請求而ajax透過JavaScript的xmlhttprequest物件發送

傳統的回應的是一個完整頁面 而JavaScript傳回所需的資料

#2.Ajax 的關鍵元素

 →JavaScript語言:Ajax技術的主要開發語言

→XML/JSON/HTML:用來封裝資料

#→DOM(文檔物件模型):修改頁面元素

→CSS:改變樣式

→Ajax引擎:即XMLHttpRequest物件

以上是Ajax與jQuery的介紹與使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板