原生js 請求ajax 內容一般分五步:
1.創建一個XMLHttpRequest異步對象
2.設置請求方式和請求地址
3.接着,用send發送請求
4.監聽狀態變化
5.最後,接收返回的數據
下面是案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp; //創建一個XMLHttpRequest異步對象
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執行代碼
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 瀏覽器執行代碼
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() //監聽狀態變化
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log(xmlhttp.responseText); //接收返回的數據
}
}
xmlhttp.open("GET","URL",true); //設置請求方式和請求地址
xmlhttp.send(); //用send發送請求
}
</script>
</head>
<body>
<button type="button" οnclick="loadXMLDoc()">獲取內容</button>
</body>
</html>