前端从零单排之AJAX(第一期)
发布时间:2020-12-16 00:34:36 所属栏目:百科 来源:网络整理
导读:ajax的使用一直是以jQuery为主,对于底层的实现有点不明觉厉。作为一个有追求的前端,这是不可以接受的。便让我们今晚好好走进ajax的内心世界。 ajax 两大特性: 在不刷新页面的情况下向服务器端发送请求 从服务器端接收数据,并进行对应的逻辑处理 ajax 请
|
ajax的使用一直是以jQuery为主,对于底层的实现有点不明觉厉。作为一个有追求的前端,这是不可以接受的。便让我们今晚好好走进ajax的内心世界。 ajax 两大特性:
ajax 请求流程 var httpRequest
if(window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
step-2 httpRequest.onreadystatechange = function(){
if(httpRequest.readyState === 4) {
// everything is good,the response is received
} else {
// still not ready
}
}
readyState 说明
Response 属性
step-3 <span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script>
(function(){
var httpRequest;
if (window.XMLHttpRequest) {
httpRequest = new XMLHttpRequest();
} else if(window.ActiveXObject) {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
if (!httpRequest) {
alert('Giving up :( (Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreaystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
httpRequest.open('GET',url);
httpRequest.send();
})()
</script>
爱心小贴士:
返回的数据为JSON时,应对数据进行相应的解析 function alertContents() {
if(httpRequest.readyState === 4) {
if(httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
} else {
alert('There was s problem with the request.');
}
}
}
参考资料
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
