day32 jQuery 進階

jQuery中的Ajax:javascript

在jQuery中,下面6種方法只有load()須要jQueryDom對象打點來調,其餘都是$直接調php

  • $.Ajax()方法屬於最底層的方法;
  • 第2層是load(),$.get(),和$.post();
  • 第3層是$.getScript()和$.getJSON()方法;

1. load() 方法

結構:load(url , [data] , [callback] )css

案例1: load(url)

<!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

image.png

案例2:頁面頭部重複引用

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>

2. $.get() 和 $.post()

load()一般是從web服務器上獲取靜態的數據文件,若是須要專遞一些參數給服務器中的頁面,可使用
$.get( ) 方法和$.post()方法(或$.ajax()方法)

結構:

  • $.get(url,[data],[callback],[type]);
  • 參數解釋:

    • data: 以json的方式傳參
    • 回調函數的參數是固定的(相似於forEach,filter那些回調,參數也是固定的)。回調含稅只有當數據成功(success)後才能被調用

      • 第一個是返回的內容responseText,能夠是XML文檔,json文件,XHML片斷等
      • 第二個是響應狀態status。 請求狀態:success error

案例:

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;
?>

返回值:

  • 返回結果爲promise對象

案例:

// 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()方法的結構和使用方法相同,不過仍然有一些區別:

get與post區別:

  • post的安全性高於get;

    • 若是以get方式請求,請求參數會拼接到url後面,安全性性低,
    • 以post方式請求,請求參數會包裹在請求體中,安全性更高;
  • 數據量區別:

    • get方式傳輸的數據量小,規定不能超過2kb,
    • post方式請求數據量大,沒有限制。
  • 傳輸速度:get的傳輸速度高於post

3. $.getScript() 和$getJson()

有時候,在頁面出現時就獲取所需的所有JavaScript文件是徹底沒有必要的,能夠在須要的時候直接加載。jQuery提供了 $.getScript( )方法來直接加載js文件,與加載一個HTML片斷同樣簡單方便,而且不須要對JavaScript文件進行處理,JavaScript文件會自動執行。

$.getScript()結構:

  • $.getScript(url,fn);

    • 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()結構:

$.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){
         處理數據...
      }
    })
  })
})

4. $.Ajax()

前面用到的$.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>

5. jQueryDom(各類API)

(1) 祖先

parent();
parents();

(2) 後代

children();
find();//必須有參數

(3) 兄弟

siblings();//除了本身以外的全部兄弟
next();
nextAll();
prev();
prevAll();

(4) 過濾 (篩選)

eq();

(5) 操做元素屬性

attr()

.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
    });

image.png

css()

// css()
    //寫
    $('#box').css({
        width: 100,
        height: 100,
        backgroundColor: "pink"
    });
    // 讀(不多用css讀屬性)
    console.log($("#box").css("width"));//100px
    //一次讀取多個值
    console.log($("#box").css(["width","height","backgroundColor"]));

(6) 寬度

  • witdh
  • innerWidth
  • outerWidth
<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>

(7) 偏移offset()

offset()自帶絕對定位

// 寫
    $("#box").offset({
        left: 200,
        top: 300
    });
    // 讀
    console.log($("#box").offset().left);//200
    console.log($("#box").offset().top);//300

(8) 滾動條高度scrollTop()

window.onscroll事件

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>

(9) index()

index();返回當前元素在父元素的下標

$("li").click(function(){
        console.log($(this).index());
    });

(10) 節點操做

建立元素節點

<script>
    //建立方法1:
    let oDiv = $("<div>");
    oDiv.html(123);
    //建立方法2:
    let oDiv = $("<div>666</div>");
    // 追加
    $("body").append(oDiv);
</script>

追加節點

1) 尾插
append()
appendTo()
let oLi = $("<li>");
    oLi.html("xixi");    
    $("ul").append(oLi);
    oLi.appendTo($("ul"));
2) 頭插
prepend()
prependTo()
$("ul").prepend(oLi);
    oLi.prependTo($("ul"));
3) 插入到目標元素以後
after()
insertAfter()
$("li").eq(2).after(oLi);
    oLi.insertAfter($("li").eq(2));
4) 插入到目標元素以前
before()
insertBefore()
$("li").eq(2).before(oLi);
    oLi.insertBefore($("li").eq(2));

6. 懶加載

1)什麼是懶加載

懶加載其實就是延遲加載,是一種對網頁性能優化的方式,好比當訪問一個頁面的時候,優先顯示可視區域的圖片而不一次性加載全部圖片,當須要顯示的時候再發送圖片請求,避免打開網頁時加載過多資源。

2) 何時用懶加載

當頁面中須要一次性載入不少圖片的時候,每每都是須要用懶加載的。

3) 懶加載原理

  • 咱們都知道HTML中的< img >標籤是表明文檔中的一個圖像;
  • < img > 標籤有一個屬性是src,用來表示圖像的URL,當這個屬性的值不爲空時,瀏覽器就會根據這個值發送請求。若是沒有src屬性,就不會發送請求。
  • 咱們先不給< img >設置src,把圖片真正的URL放在另外一個屬性data-src中,在須要的時候也就是圖片進入可視區域的以前,將URL取出放到src中。

4) 須要用到知識點

(1) 圖片距離頂部的高度:

  • img.offsetTop

(2) 當前窗口的高度:

  • window.innerHeight

(3) 滾動條滾動的高度:

  • document.body.scrollTop || document.documentElement.scrollTop

5) 加載圖片的判斷條件

圖片距離頂部的距離 < 瀏覽器滾動條滾動的高度 + 瀏覽器窗口的高度

相關文章
相關標籤/搜索