使用原生js請求ajax

原生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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章