標籤:發送資料 echo one 開始 頁面 encode 屬性 響應 方式
非同步對象
a)建立非同步對象
b)佈建要求的url等參數
c) 發送請求
d)註冊時間
e)在註冊的事件中擷取返回的內容並修改頁面顯示的內容
布爾類型不能直接用echo輸出
常見的響應狀態Ajax概念
在瀏覽器中,我們也能夠不重新整理頁面
,通過ajax
的方式去擷取一些新的內容,類似網頁有微博
,朋友圈
,郵箱
等
Asynchronous Javascript And XML
(非同步JavaScript和XML),
他並不是憑空出現的新技術,而是對於現有技術的結合:核心是js對象XMLHttpRequest
XMLHttpRequest
ajax
使用的依舊是HTTP請求
,那麼讓我們來回憶一下一個完整的HTTP請求
需要什麼
>
請求的網址,方法get/post
提交請求內容資料
,請求主體
等
接收響應回來的內容
五步使用法:
建立XMLHTTPRequest對象
註冊回呼函數
使用open方法設定和伺服器端互動的基本資料
設定發送的資料,開始和伺服器端互動
更新介面
XMLHttpRequest_API講解
1.建立
XMLHttpRequest
對象(相容性寫法)
var xml=new XMLHttpRequest();
var xml=new ActiveXObject("Microsoft.XMLHTTP");
var request ; if(XMLHttpRequest){ // 新式瀏覽器寫法 request = new XMLHttpRequest(); }else{ //IE5,IE6寫法 request = new ActiveXObject("Microsoft.XMLHTTP"); }
2.發送請求:
方法 |
描述 |
open(method,url,async) |
規定請求的類型、URL 以及是否非同步處理請求。
-
- method:請求的類型;GET 或 POST
- url:檔案在伺服器上的位置
- async:true(非同步)或 false(同步)
|
send(string) |
將請求發送到伺服器。
|
3.POST請求注意點:
如果想要像form
表單提交資料那樣使用POST
請求,需要使用XMLHttpRequest
對象的setRequestHeader()
方法 來添加 HTTP 頭。然後在 send() 方法中添加想要發送的資料:
xmlhttp.open("POST","ajax_test.php",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("fname=Bill&lname=Gates");
4.onreadystatechange事件
當伺服器給予我們反饋時,我們需要實現一些邏輯
屬性 |
描述 |
onreadystatechange |
儲存函數(或函數名),每當 readyState 屬性改變時,就會調用該函數。 |
readyState |
存有 XMLHttpRequest 的狀態。從 0 到 4 發生變化。
-
- 0: 請求未初始化
- 1: 伺服器串連已建立
- 2: 請求已接收
- 3: 請求處理中
- 4: 請求已完成,且響應已就緒
|
status |
200: "OK" 404: 未找到頁面 |
4.伺服器響應內容
如果響應的是一般字元串,使用responseText
,如果響應的是XML
,使用responseXML
屬性 |
描述 |
responseText |
獲得字串形式的響應資料。 |
responseXML |
獲得 XML 形式的響應資料。 |
get的資料,直接在請求的url
中添加即可
<script type="text/javascript"> // 建立XMLHttpRequest 對象 var xml = new XMLHttpRequest(); // 設定跟服務端互動的資訊 xml.open(‘get‘,‘01.ajax.php?name=fox‘); xml.send(null); // get請求這裡寫null即可 // 接收伺服器反饋 xhr.onreadystatechange = function () { // 這步為判斷伺服器是否正確響應 if (xhr.readyState == 4 && xhr.status == 200) { // 列印響應內容 alert(xml.responseText); } };</script>
<script type="text/javascript"> // 非同步對象 var xhr = new XMLHttpRequest(); // 設定屬性 xhr.open(‘post‘, ‘02.post.php‘ ); // 如果想要使用post提交資料,必須添加 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 將資料通過send方法傳遞 xhr.send(‘name=fox&age=18‘); // 發送並接受傳回值 xhr.onreadystatechange = function () { // 這步為判斷伺服器是否正確響應 if (xhr.readyState == 4 && xhr.status == 200) { alert(xhr.responseText); } };</script>
PHP. 02®. Ajax非同步處理、常見的響應狀態、XMLHttpRequest對象及API、ajax的get/post方法、