ajax实现原理解释,ajax 实现原理

平时我们在做项目时通常利用jQuery封装好的ajax函数:$.ajax(),

$.get(),$.post(),用起来很方便,但是很多小伙伴都不知道ajax底层实现原理,了解原理有助于我们更好的开发,拓展

#######Ajax:异步的ajax和xml

建立XMLHttpRequest对象

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

2.设置回调函数

XmlHttp.onreadyStatechange = callback;

callback=function(){}

3.与服务器建立连接并向服务器发送请求

xmlhttp.open("GET","test1.txt",true);

xmlhttp.send();

9480a77c8c57

图片来自w3school手册

get请求写法:

xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);

xmlhttp.send();

post请求需加请求头

xmlhttp.open("POST","ajax_test.asp",true);

xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");

xmlhttp.send("fname=Bill&lname=Gates");

9480a77c8c57

图片来自w3school手册

4.服务器响应,在回调函数中对不同状态作出处理

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

}

}

如需获得来自服务器的响应,用 XMLHttpRequest 对象的 responseText 或 responseXML 属性

9480a77c8c57

Paste_Image.png

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

9480a77c8c57

图片来自w3chool手册

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值