第一步:獲得XMLHttpRequest對象;
var ajax = new XMLHttpRequest();
第二步:設置狀態監聽函數
ajax.onreadystatechange = function(){}
第三步:open一個請求:
- 其中,第一個參數為傳遞方式:get/post;
- 第二個參數:請求數據的url地址;
- 第三個參數:true/false。true表示異步請求。false表示同步請求
ajax.open("GET","user.json",true);
第四步:send一個請求。可以發送對象和字符串,不需要傳遞數據發送null;
ajax.send(null);
第五步,在監聽函數中,判斷readyState==4 && status == 200表示請求成功;
if (ajax.readyState == 4 && ajax.status == 200) {}
第六步,使用ajax.responseText、ajax.responseXML接收響應數據,并使用原生js操作DOM進行顯示;
console.log(JSON.parse(ajax.responseText));
完整代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax</title>
<script type="text/javascript">
//第一步:獲得XMLHttpRequest對象
var ajax = new XMLHttpRequest();
//第二步:設置狀態監聽函數
ajax.onreadystatechange = function(){
//console.log(ajax.readyState);
//console.log(ajax.status);
//第五步,在監聽函數中,判斷readyState==4 && status == 200表示請求成功;
if (ajax.readyState == 4 && ajax.status == 200) {
//第六步,使用ajax.responseText、ajax.responseXML接收響應數據,并使用原生js操作DOM進行顯示
//console.log(ajax.responseText);
//console.log(ajax.responseXML);//返回不是XMl,顯示null
console.log(JSON.parse(ajax.responseText));
//console.log(eval("("+ajax.responseText+")"));
}
}
//第三步:open一個請求
ajax.open("GET","user.json",true); //true表示異步請求。false表示同步請求
//第四步:send一個請求。可以發送對象和字符串,不需要傳遞數據發送null;
ajax.send(null);
var str = "alert('666')";
eval(str);
eval("alert('666')");
var jsonU = "{'name':'jack'}";
console.log(eval("("+jsonU+")"));
</script>
</head>
<body>
</body>
</html>