jq的實作方法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button>點擊</button>
</body>
<script src="js/jquery-2.1.4.min.js"></script>
<script>
$('button').click(function() {
$.ajax({
url: '/ajax/ajax/a.txt', //請求路徑
type: 'GET', //請求方式
async: true, //同步異步
dataType: 'text',//回傳資料型別
data: '噢噢噢噢', //發送資料到后臺
success: function(data) { //請求成功拿到資料
console.log(data);
},
error:function(err){//提供報錯資訊
console.log(err);
}
})
})
</script>
</html>
原生實作方法:(以get方法為例)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!--
1, 這塊首先要處理一個兼容問題,因為在低版本的IE下,是不存在XMLHttpRequest內置物件,
我們可以使用另一個物件ActiveXObject('Microsoft.XMLHTTP')替代就可以,
XMLHttpRequest 新瀏覽器
ActiveXObject("Microsoft.XMLHTTP"); 舊瀏覽器
2,
xhr.open(method,url,async)
method: get post
url: 請求地址
async: ture(異步) flase(同步)
3,
xhr.send() 發送請求
通過get方式發送的請求, xhr.send(null)
通過post方式發送的請求, xhr.send("user=zf")
4, 監聽
xhr.onreadystatechange 當狀態碼改變時觸發
5, 接收資料,
responseText 接收回應的資料 (字串格式)
get 與 post 的區別:
POST是發送資料,GET是接受資料;
POST發送資料的安全性較好,而GET較差;
POST發送資料不限制大小,而GET大小受限2~100k,
-->
<script>
//宣告ajax核心物件, 處理兼容
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} else {
alert('瀏覽器很垃圾,換吧');
}
//建立連接
xhr.open("GET", "http://localhost/speed/a.txt", true);
//發送請求
xhr.send(null);
//監聽狀態碼
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//接收資料
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/157645.html
標籤:其他
