ajax的基本概念及其使用
阿新 • • 發佈:2019-02-20
XMLHttpRequest
ajax使用的依舊是HTTP請求,那麼讓我們來回憶一下一個完整的HTTP請求需要什麼
- 請求的網址,方法get/post
- 提交請求內容資料,請求主體等
- 接收響應回來的內容
五步使用法:
- 建立XMLHTTPRequest物件
- 註冊回撥函式,當伺服器迴應我們了,我們想要執行什麼邏輯
- 使用open方法設定和伺服器端互動的基本資訊,設定提交的網址,資料,post提交的一些額外內容
- 設定傳送的資料,開始和伺服器端互動,傳送資料
- 更新介面,在註冊的回撥函式中,獲取返回的資料,更新介面
程式碼示例:get
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>
程式碼示例:post
<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>