jQuery中的Ajax:javascript
在jQuery中,下面6種方法只有load()須要jQueryDom對象打點來調,其餘都是$直接調php
結構:load(url , [data] , [callback] )css
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="box"> </div> </body> </html> <script src="myjQuery.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function(){ //load方法加載html $("#box").load("test.html"); }); </script>
test.html 文件html
hello world;java
結果:將url返回的內容當作該元素的innerHTML。web
load.html文件ajax
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> * { margin: 0; padding: 0; } header { height: 100px; background: yellow; } header ul { height: 100px; width: 800px; position: relative; margin: 0 auto; opacity: 0.5; } header ul li { list-style: none; width: 150px; background: red; text-align: center; line-height: 100px; border: 1px solid black; float: left; } section { height: 300px; background: green; opacity: 0.3; } footer { height: 300px; background: blue; opacity: 0.3; } </style> </head> <body> <header> </header> <section> </section> <footer> </footer> </body> </html> <script src="jQuery.js"></script> <script type="text/javascript"> $('header').load("head.html",function(){ $("li").click(function(){ console.log($(this).html()); }); }); </script>
head.html文件(直接是代碼,不須要寫html head body等那些結構)json
<ul> <li>主題1</li> <li>主題2</li> <li>主題3</li> <li>主題4</li> <li>主題5</li> </ul>
改進,即在當前頁面(2-header.html),只要load頭部文件便可。當前頁面不須要寫css js(將html css js 都整合在2-head.html中)數組
2-header.htmlpromise
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <header> </header> <section> </section> <footer> </footer> </body> </html> <script src="../jQuery.js"></script> <script type="text/javascript"> $("header").load("2-head.html"); </script>
2-head.html
<link rel="stylesheet" type="text/css" href="2-head.css"/> <ul> <li>主題1</li> <li>主題2</li> <li>主題3</li> <li>主題4</li> <li>主題5</li> </ul> <script src='2-head.js'></script>
2-head.js
$("li").click(function() { console.log($(this).html()); });
2-head.css 略
篩選載入的HTML文檔
若是隻要加載頁面內的某些內容,可使用load(URL selector)方法的URL參數來達到目的。
注意:URL和選擇器之間有一個空格
<script type="text/javascript"> //只請求2-head.html中的ul,其餘以及link script都請求 $("header").load("2-head.html ul"); </script>
load()一般是從web服務器上獲取靜態的數據文件,若是須要專遞一些參數給服務器中的頁面,可使用
$.get( ) 方法和$.post()方法(或$.ajax()方法)
參數解釋:
回調函數的參數是固定的(相似於forEach,filter那些回調,參數也是固定的)。回調含稅只有當數據成功(success)後才能被調用。
案例:
html文件:
<script src="../jQuery.js"></script> <script type="text/javascript"> //注意: 運行php文件須要打開phpStudy軟件做爲服務器,並使用服務器地址運行代碼 $.get("3-getAndPost.php",{name:"xiaoming",age:18},function(resText,status){ console.log(resText);//xiaoming 18 console.log(status);//success }); </script>
3-getAndPost.php
<?php header("Content/type:text/xtml;charset=utf-8"); $name = $_REQUEST["name"]; $age = $_REQUEST["age"]; echo $name . ' ' . $age; ?>
案例:
// get和post的返回值: promise對象 // $.get().then(成功的回調, 失敗的回調) $.get("3-getAndPost.php",{name:"xiaohong",age:20},function(res){ console.log(res);//xiaohong 20 }).then(function(resText,status){ console.log(resText);//xiaohong 20 console.log(status);//success },function(){ console.log("失敗"); })
由於使用方法相同,所以只要改變jQuery函數,就能夠將程序在GET請求和POST請求之間切換;
$.post() 方法和$get()方法的結構和使用方法相同,不過仍然有一些區別:
post的安全性高於get;
數據量區別:
有時候,在頁面出現時就獲取所需的所有JavaScript文件是徹底沒有必要的,能夠在須要的時候直接加載。jQuery提供了 $.getScript( )方法來直接加載js文件,與加載一個HTML片斷同樣簡單方便,而且不須要對JavaScript文件進行處理,JavaScript文件會自動執行。
$.getScript(url,fn);
html文件:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style type="text/css"> #box { width: 100px; height: 100px; border: 1px solid red; } </style> </head> <body> <div id="box"> </div> </body> </html> <script src="../jQuery.js"></script> <script type="text/javascript"> $.getScript("4-getScript.js",function(){ changeColor($("#box")); }); </script>
4-getScript.js
function changeColor(obj) { let color = "#"; let str = "0123456789abcdef"; for (let i = 0; i < 6; i++) { color += str.charAt(Math.round(Math.random() * 15)); } obj.css({ backgroundColor: color }); }
$.getJson( )方法用於加載JSON文件,與$.getScript( )方法的用法相同;
$.getJSON( url,回調函數);
當點擊加載時,頁面上看不到任何效果,雖然函數加載了JSON文件,可是並無告知JavaScript對返回的數據如何處理,爲此,因此在回調函數裏咱們能夠處理返回的數據
一般咱們須要遍歷咱們獲得的數據,雖然這裏咱們可使用傳統的for循環,可是咱們也能夠經過$.each(),能夠用來遍歷對象和數組,$.each()函數是以一個數組或者對象爲第1個參數,以一個回調函數做爲第2個參數,回調函數擁有兩個參數,第1個爲對象的成員或者數組的下標,第2個位對應變量或內容
$(function(){ $("button").click(function(){ $.getJSON( "text.json" , function( data ){ $.each( data , function(index,comment){ 處理數據... } }) }) })
前面用到的$.load(),$.get(),$.post(),$.getScript(),$.getJSON()這些方法,都是基於$.ajax()方法構建的,$.ajax()是jQuery最底層的Ajax實現,由於能夠用來代替前面的全部方法。
因此若是除了上面,還須要編寫一下複雜的Ajax程序,那麼就要用$.ajax()。
$.ajax({ url: 請求地址, type: "get(默認)"/"post"/"put"/"delete", data: 請求參數 {id:123,pwd:456}, //dataType:請求數據類型"html | text | json | xml | script | jsonp ", success:function(data,dataTextStatus,jqxhr){ },//請求成功時 error:function(jqxhr,textStatus,error)//請求失敗時 });
<script type="text/javascript"> $.ajax({ url:"3-getAndPost.php", type:"get", data:{ name: "彭于晏", age: "18" }, success:function(resText){ console.log(resText);//彭于晏 18 } }); </script>
parent(); parents();
children(); find();//必須有參數
siblings();//除了本身以外的全部兄弟 next(); nextAll(); prev(); prevAll();
eq();
.attr(); .prop(); //二者區別: input的checked屬性 console.log($("input").attr("checked"));//checked console.log($("input").prop("checked"));//true 因此true/false對於邏輯判斷更經常使用
let oBox = document.getElementById("box"); // 原生修改屬性值 oBox.id = "heihei"; // 原生讀取屬性值 console.log(oBox.id);//heihei
//一個參數爲讀 console.log($("#box").attr("id"));//xixi //兩個參數爲改或者添加 $("#box").attr("id","xixi"); $('#xixi').attr("name","oBox"); // 添加多個屬性 $("#xixi").attr({ a:1, b:2, c:3 });
// css() //寫 $('#box').css({ width: 100, height: 100, backgroundColor: "pink" }); // 讀(不多用css讀屬性) console.log($("#box").css("width"));//100px //一次讀取多個值 console.log($("#box").css(["width","height","backgroundColor"]));
<style type="text/css"> #box{ width: 100px; height: 100px; background: #0000FF; border: 10px solid red; padding: 20px; } </style> <script src="jQuery.js"></script> <script type="text/javascript"> console.log($("#box").width());//content 100 console.log($("#box").innerWidth());//content+padding 100+20*2= 140 console.log($("#box").outerWidth());//content+padding+border 100+2*20+10*2=160 </script>
offset()自帶絕對定位
// 寫 $("#box").offset({ left: 200, top: 300 }); // 讀 console.log($("#box").offset().left);//200 console.log($("#box").offset().top);//300
window.onscroll = function(){ console.log($(window).scrollTop()); }
<style type="text/css"> body{ height: 1000px; } </style> <body> <button type="button">返回頂端</button> </body> <script> $("button").click(function(){ $(window).scrollTop(0); }) </script>
index();返回當前元素在父元素的下標
$("li").click(function(){ console.log($(this).index()); });
<script> //建立方法1: let oDiv = $("<div>"); oDiv.html(123); //建立方法2: let oDiv = $("<div>666</div>"); // 追加 $("body").append(oDiv); </script>
let oLi = $("<li>"); oLi.html("xixi"); $("ul").append(oLi); oLi.appendTo($("ul"));
$("ul").prepend(oLi); oLi.prependTo($("ul"));
$("li").eq(2).after(oLi); oLi.insertAfter($("li").eq(2));
$("li").eq(2).before(oLi); oLi.insertBefore($("li").eq(2));
懶加載其實就是延遲加載,是一種對網頁性能優化的方式,好比當訪問一個頁面的時候,優先顯示可視區域的圖片而不一次性加載全部圖片,當須要顯示的時候再發送圖片請求,避免打開網頁時加載過多資源。
當頁面中須要一次性載入不少圖片的時候,每每都是須要用懶加載的。
(1) 圖片距離頂部的高度:
(2) 當前窗口的高度:
(3) 滾動條滾動的高度:
圖片距離頂部的距離 < 瀏覽器滾動條滾動的高度 + 瀏覽器窗口的高度