Flask + Ajax + Mysql 實現網頁非同步載入(二)
阿新 • • 發佈:2018-11-13
Flask + Ajax + Mysql 實現網頁非同步載入(一)
二、jquery 和Ajax 實現前端請求
<script src="static/js/jquery.min.js" > </script> <script type="text/javascript"> var pk = 1; $(window).scroll(function () { //下面這句主要是獲取網頁的總高度,主要是考慮相容性所以把Ie支援的documentElement也寫了,這個方法至少支援IE8 var htmlHeight = $(document).height(); //clientHeight是網頁在瀏覽器中的可視高度, var clientHeight = $(window).height(); //scrollTop滾動條到頂部的垂直高度 var scrollTop = $(document).scrollTop(); //通過判斷滾動條的top位置與可視網頁之和與整個網頁的高度是否相等來決定是否載入內容; var he = scrollTop + clientHeight; if (he == htmlHeight ) { pk = pk +1; //每次和後端互動,page+1。 addListMore(); } if (scrollTop <=0){ refresh(); } //console.log("滾動條位置:" + scrollTop); //console.log("可視高度:" + clientHeight); //console.log("網頁總高度" + htmlHeight); }); function addListMore() { //console.log("載入更多"); $.ajax({ type:"GET", url:"/?page="+pk, dataType:"html", success:function (data) { //var $data = $(data); //var target_div = $data.find("#div1"); //$("body").append(target_div); $("#div2").empty(); var div = document.createElement("div"); document.body.appendChild(div); div.innerHTML = data; } }) } function refresh() { $.ajax({ type:"GET", url:"/", dataType:"html", success:function () { window.location.reload(); //location.href = url + "/teacherList"; } }) } </script>
主要有三個問題:
1、判斷滾動位置+可視高度=網頁總高度。
2、如何改變url的page引數.
3、ajax 的success:function(data){ } 如何把伺服器端傳送過來的html載入到當前頁面的後面。
var div = document.createElement("div");
document.body.appendChild(div);
div.innerHTML = data;
這三句實現了把data,也就是返回的index.html 作為div顯示在當前網頁上。