一.AJAX原理和封裝
1.服務器環(huán)境的搭建
省略...
2.第一個ajax程序
-
什么是Ajax
Asynchronous Javascript and XML(異步的javascript和XML)
-節(jié)省用戶操作,時間,提高用戶體驗,減少數(shù)據(jù)請求
-傳輸獲取數(shù)據(jù) -
使用Ajax
使用ajax獲取某一個文本文件的內(nèi)容 -
Ajax過程詳解
創(chuàng)建對象XMLHttpRequest()- Date()對象
-ActiveXObject('Microsoft.XMLHTTP')
- Date()對象
3.ajax流程對象的創(chuàng)建和兼容
window.onload=function(){
var oBtn=document.getElementById("btn");
oBtn.onclick=function(){
/*1.創(chuàng)建一個ajax對象 ie6一下用的是new AcitveXObject('Mircosoft.XMLHTTP')*/
var xhr=null
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
/*
try{
xhr=new XMLHttpRequest();
}catch(e){
xhr=new AcitveXObject("Mirosoft.XMLHTTP")
}
*/
/*寫入地址*/
xhr.open("get","1.txt",true);
/*發(fā)送*/
xhr.send();
/*監(jiān)聽*/
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
alert(xhr.responseText)
}
}
}
}
4.ajax流程-open方法和表單
表單:數(shù)據(jù)的提交
action : 數(shù)據(jù)提交的地址,默認是當前頁面
method : 數(shù)據(jù)提交的方式,默認是get方式
1.get
把數(shù)據(jù)名稱和數(shù)據(jù)值用=連接,如果有多個的話,那么他會把多個數(shù)據(jù)組合&進行連接,然后把數(shù)據(jù)放到url?后面?zhèn)鞯街付撁?br>
url長度限制的原因,我們不要通過get方式傳遞過多的數(shù)據(jù)
2.post
理論上無限制,
enctype : 提交的數(shù)據(jù)的格式,默認application/x-www-form-urlencoded
window.onload=function(){
var oBtn=document.getElementById("btn");
oBtn.onclick=function(){
/*1.創(chuàng)建一個ajax對象 ie6以下用的是new AcitveXObject('Mircosoft.XMLHTTP')*/
var xhr=null
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
/*提交請求*/
/*
* open方法
* 參數(shù):
* 1.打開方式
* 2.地址
* 3.是否異步
* 異步:非阻塞 前面的代碼不會影響后面的代碼執(zhí)行
* 同步:阻塞 前面的代碼會影響后面的代碼執(zhí)行 false 一般情況下是不會用同步的直接寫在監(jiān)聽里就好了
* */
xhr.open("get","1.txt",true);
/*發(fā)送請求*/
xhr.send();
/*監(jiān)聽等待服務器返回內(nèi)容*/
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
alert(xhr.responseText)
}
}
}
}
5.ajax流程-數(shù)據(jù)的獲取
請求狀態(tài)監(jiān)控
-
onreadystatechange
-
readyState 屬性 : 請求狀態(tài)
0 (初始化) 還沒有調(diào)用open() 方法
1 (載入) 已調(diào)用send()方法, 已收到全部響應內(nèi)容
2 (載入完成) send()方法完成,已收到全部響應內(nèi)容
3 (解析) 正在解析響應內(nèi)容
4 (完成) 響應內(nèi)容解析完成,可以再客戶端調(diào)用了 - status屬性 : 服務器(請求資源)的狀態(tài)
-
返回的內(nèi)容
-responseText :返回以文本形式存放的內(nèi)容
-responseXML : 返回XML形式的內(nèi)容
-
readyState 屬性 : 請求狀態(tài)
/*監(jiān)聽等待服務器返回內(nèi)容
* readyState : ajax工作狀態(tài)
* responseText : ajax請求的內(nèi)容就被存放到這個屬性下面 類型是字符串類型
* on readystate change : 當readyState改變的時候觸發(fā)
* status : 服務器狀態(tài)---http狀態(tài)碼
* */
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status==200){
alert(xhr.responseText)
}else{
alert(xhr.status)
}
}
}
6.應用中g(shù)et和post的區(qū)別處理
get請求
oBtn.onclick=function(){
var xhr=null
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
/*
* 1.解決緩存問題 在url?后邊連接一個隨機數(shù) 時間戳
* 2.亂碼,編碼encodeURI
* */
xhr.open("get",'get.php?username='+encodeURI("名字")+'&age=30&'+new Date().getTime(),true);
xhr.send();
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status==200){
alert(xhr.responseText)
}else{
alert(xhr.status)
}
}
}
}
post請求
oBtn.onclick=function(){
var xhr=null
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
xhr.open("post",'post.php',true);
//post方式,數(shù)據(jù)放在send()里作為參數(shù)發(fā)送
//告訴后端發(fā)送數(shù)據(jù)的類型 post沒有緩存問題 無需編碼
xhr.setRequestHeader("content-type",'application/x-www-form-urlencoded');
xhr.send('username=leo&age=30');
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status==200){
alert(xhr.responseText)
}else{
alert(xhr.status)
}
}
}
}
7.ajax獲取數(shù)據(jù)的處理和實例
注:嚴格的Json的key值一定要用雙引號括起來
JSON.stringify() 可以把一個對象轉(zhuǎn)化成對應字符串
JSON.parse() :可以把字符串轉(zhuǎn)成對應對象
實例:ajax的封裝及實例
//php:
header("content-type:text/html;charset='utf-8'");
error_reporting(0);
$news=array(
array('title'=>'法餐烹飪小知識 —— 法式煎蛋','date'=>'2017-1-4'),
array('title'=>'自抱自泣部凑!早知道我一個人住的小公寓就應該這樣裝!','date'=>'2017-2-5'),
array('title'=>'堅持寫手賬二十一天,我收獲了什么','date'=>'2017-3-6'),
array('title'=>'過日子要有技術(shù)含量:這些東西讓你的衣食住行更有質(zhì)量','date'=>'2017-6-6'),
array('title'=>'開胃易消化檀训、補鈣解便秘王带!寶寶吃慣了粥,換成這個更愛吃件炉!','date'=>'2017-8-25'),
array('title'=>'大衣指南|跟隨時尚的小妖精來學穿大衣','date'=>'2017-9-12'),
array('title'=>'情人節(jié)特輯勘究,淘寶上有哪些值得你收藏的禮物','date'=>'2017-10-22'),
array('title'=>'治療失眠癥的這4個方法,希望對你有用','date'=>'2017-11-22')
);
echo JSON_encode($news);
//js:
function ajax(method,url,data,success){
var xhr=null
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
if(method=='get'&& data){
url+='?'+data;
}
xhr.open(method,url,true);
if(method=='get'){
xhr.send();
}else{
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(data);
}
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status==200){
success&&success(xhr.responseText);
}else{
alert(xhr.status)
}
}
}
}
window.onload=function(){
var oBtn=document.getElementById("btn");
oBtn.onclick=function(){
ajax('get','get.php','',function(data){
var data=JSON.parse(data);
var oUl=document.getElementById("ul");
var html="";
for(var i=0;i<data.length;i++){
html+='<li><a href="">'+data[i].title+' '+data[i].date+'</a></li>';
}
oUl.innerHTML=html;
});
}
}
二.AJAX實例:留言板&瀑布流
瀑布流案例 :
*{margin:0;padding:0;}
#ul{width:1080px;margin:100px auto 0;}
li{width:247px;list-style:none;float:left;margin-right:10px;}
li div{border:1px solid #000;padding:10px;margin-bottom:10px;}
li div img{width:225px;display:block;}
<ul id="ul">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
function ajax(method,url,data,success){
var xhr=null
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
if(method==='get'&& data){
url+='?'+data;
}
xhr.open(method,url,true);
if(method==='get'){
xhr.send();
}else{
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.send(data);
}
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status===200){
success&&success(xhr.responseText);
}else{
alert(xhr.status)
}
}
}
}
window.onload=function(){
var oUl=document.getElementById("ul");
var aLi=oUl.getElementsByTagName("li");
var iLen=aLi.length;
var iPage=1;
var onOff=true;
getList();
function getList(){
ajax('get','getPics.php','cpage='+iPage,function(data){
var data=JSON.parse(data);
if(!data.length){//后續(xù)沒有數(shù)據(jù)了
return;
}
for(var i=0;i<data.length;i++){
var _index=getShort();
var oDiv=document.createElement("div");
var oImg=document.createElement("img");
oImg.src=data[i].preview;
oImg.style.height=data[i].height*(225/data[i].width)+"px";
oDiv.appendChild(oImg);
var oP=document.createElement("p");
oDiv.appendChild(oP);
aLi[_index].appendChild(oDiv);
}
onOff=true;
})
}
window.onscroll=function(){
var _index=getShort();
var oLi=aLi[_index];
var scrollTop=document.documentElement.scrollTop || document.body.scrollTop;
if(getTop(oLi)+oLi.offsetHeight<(document.documentElement.clientHeight+scrollTop)){
if(onOff){
onOff=false;
iPage++;
getList();
}
}
}
function getShort(){
var index=0;
var ih=aLi[index].offsetHeight;
for(var i=0;i<iLen;i++){
if(aLi[i].offsetHeight<ih){
index=i;
ih=aLi[i].offsetHeight;
}
}
return index;
}
function getTop(obj){
var iTop=0;
while(obj){
iTop=obj.offsetTop;
obj=obj.offsetParent;
}
return iTop;
}
}
//php內(nèi)容
<?php
header('Content-type:text/html; charset="utf-8"');
/*
API:
getPics.php
參數(shù)
cpage : 獲取數(shù)據(jù)的頁數(shù)
*/
$cpage = isset($_GET['cpage']) ? $_GET['cpage'] : 1;
$url = 'http://www.wookmark.com/api/json/popular?page=' . $cpage;
$content = file_get_contents($url);
$content = iconv('gbk', 'utf-8', $content);
echo $content;
?>
三.AJAX跨域解決方案:JSONP
1.問題的回復及跨域限制問題
-
跨域的問題
域:域名
跨域請求(訪問):一個域名下的文件請求另一個域名下的資源,就產(chǎn)生了跨域 -
跨域的解決
jsonp: json padding
2.跨域的解決
JSONP: JSON with Padding
1.script標簽
2.用script標簽加載資源是沒有跨域問題的
在資源加載進來之前定義好一個函數(shù),這個函數(shù)接收一個參數(shù)(數(shù)據(jù)),函數(shù)里面利用這個參數(shù)做一些事情
然后需要的時候,通過script標簽加載對應遠程文件資源,當遠程的文件資源被加載進來的時候,就會去執(zhí)行我們前面定義好的函數(shù),并且把數(shù)據(jù)當做這個函數(shù)的參數(shù)傳入進去
比如:點擊按鈕時 創(chuàng)建script 寫入地址 append進去
實例:百度下拉實例
<style>
#q{width:300px;height:30px;padding:5px;border:1px solid #f90;font-size:16px;}
#ul{border:1px solid #f90;width:310px;margin:0;padding:0;display:none;}
li a{line-height:30px;padding:5px;text-decoration:none;color:#666;display:block;}
li:hover{background:#f40;}
</style>
<input type="text" id="q">
<ul id="ul"></ul>
<script>
function miaov(data){
var oUl=document.getElementById("ul");
var html="";
if(data.s.length){
for(var i=0;i<data.s.length;i++){
html+='<li><a target="_blank"
}
oUl.innerHTML=html;
oUl.style.display='block';
}else{
oUl.style.display="none";
}
}
window.onload=function(){
var oQ=document.getElementById("q");
var oUl=document.getElementById("ul");
oQ.onkeyup=function(){
if(this.value!=""){
var oScript=document.createElement('script');
oScript.src="https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+this.value+"&cb=miaov";
document.body.appendChild(oScript);
}
}
}
</script>