Ajax快速入門

來源:互聯網
上載者:User

標籤:

Ajax快速入門

2015-1-28????早 8:00

1.如何建立XHR對象

答:按標準 new XMLHttpRequest()即可以得到

????考慮低版本IE 可以使用new window.ActiveXObject((‘Microsoft.XMLHTTP‘));

????相容性建立:

????function createXHR(){

????????var xhr = null;

????????if(window.XMLHttpRequest){

????????????xhr = new XMLHttpRequest();

????????}else if(window.ActiveXObject){

????????????xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘);

????????}

????????return xhr;

}

?

2.如何利用XHR來發送請求

答:分析HTTP協議,要請求需要明確一下幾個因素:

????(1).用什麼方法請求

????????GET, POST, PUT, DELETE, HEAD

????(2).請求哪個資源?(url)

????(3).同步方式:同步/非同步?

????????true:非同步 false:同步

????????同步:程式順序執行,傳回值儲存到xhr.responseText中

????????非同步:html不用等待php返回,直接向下執行

?

?

單向投票代碼:

????script代碼:

function vote(){

????????//1.製造XHR

????????var xhr = createXHR();

????????//2.開啟串連

????????xhr.open(‘GET‘,‘./vote.php‘,true); //true:非同步 false:同步

????????//3.發送請求

????????xhr.send(null);

????????//alert("ok");

????????//綁定狀態變化的回呼函數

????????xhr.onreadystatechange = function(){

????????????var pg = document.getElementById(‘progress‘);

if(this.readyState == 4 && this.responseText == 1)

????????????????alert("投票成功了")????????

pg.innerHTML = pg.innerHTML +‘狀態現在變成‘ +this.readyState;

????????}

?

}????

html代碼:

<div>

????<p><img src="a.png"/></p>

????<p><input type="button" value="投票方法1" onclick="vote();"/></p>

????<div id="progress"></div>

?

</div>

vote.php中代碼:

????<?php

????????//此處 sleep(2); //觀察同步和非同步效果

$cnt = file_get_contents(‘./vote.txt‘);

$cnt += 1;

file_put_contents(‘./vote.txt‘,$cnt);

?>

?

3.如何擷取請求的返回資料

答:XHR對象本身有一個屬性:responseText 代表傳回值

????xhr.open(‘GET‘,‘./02-vote.php‘,false);

alert(xhr.responseText);

?

4.如果使用非同步,程式不等待響應而繼續向下執行,如何知道之前的請求已經完成

答:XHR對象在請求與響應過程中,狀態會不斷髮生變化(0-4)逐步變化

????我們可以綁定一個函數,監聽狀態的變化,只要狀態變化就觸發某個函數

????//綁定狀態變化的回呼函數

????xhr.onreadystatechange = function(){

????????var pg = document.getElementById(‘progress‘);

if(this.readyState == 4 && this.responseText == 1)

????????????alert("投票成功了")????????

pg.innerHTML = pg.innerHTML +‘狀態現在變成‘ +this.readyState;

????}

????

????XHR 的readyState當變到4時,就意味著請求完畢。

?

?

Ajax快速入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.