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) 滚动条滚动的高度:
图片距离顶部的距离 < 浏览器滚动条滚动的高度 + 浏览器窗口的高度