【Ajax】初谈
本质,利用浏览器上XMLhttpRequest
<html>
<head>
</head>
<body>
<script>
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
// 已经接收到全部响应数据,执行以下操作
var data = xhr.responseText;
console.log(data);
}
};
xhr.open('POST', "/test/", true );
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
xhr.send('n1=1;n2=2;');
</script>
</body>
</html>
利用jQuery类库,内部封装,使用简单了。
<html>
...
<body>
<script src='jquery.js'></script>
<script>
$.ajax({
url:"....",
type:"post",
data:{n1:123,n2:456},
success:function(res){
console.log(res);
}
})
</script>
</body>
</html>
大致的应用场景:
- 提交数据,页面可以刷新 -> form表单
- 提交数据,不想刷新,ajax形式提交。