Native Ajax | 原生 Ajax

Background: Before understanding Ajax, there were existing ways of sending requests:
1. Entering a URL in the address bar, hitting enter, and refreshing the page.
2. Using the 'href' or 'src' attributes of specific elements.
3. Submitting forms. However, none of these methods involved making changes programmatically.

Solution: The solution is to use a set of APIs provided by web browsers called Ajax. Ajax can address issues like fetching data on demand, validating user data, automatically updating page content, and enhancing the user experience with seamless, non-refreshing page interactions.

Native Ajax code example:
<script>

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://~~/users");
xhr.send(null);
xhr.onreadystatechange = function() {
    if (this.readyState === 4) {
        console.log(this.responseText);
    }
}


</script>

For compatibility with IE6:

var xhr = null;
window.XMLHttpRequest ? (xhr = new XMLHttpRequest()) : (xhr = new ActiveXObject("Microsoft.XMLHTTP"));

If using the POST method, you need to set the request header:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 

And correspondingly send data like:
xhr.send("name=Kevin&sex=male&age=10");

Or, if using JSON:
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send("json formatted string");


背景: 在了解Ajax之前,已有的发送请求的方式有:1. 地址栏输入的地址,点击回车,刷新页面;2. 特定的元素的href或src 3. 表单提交。但是这些都不是通过代码的方式进行变成操作的。

解决:使用浏览器提供的一套API - Ajax。可以解决按需获取数据,对用户数据校验,自动更新页面内容和提升用户体验感无刷新页面的体验感等问题。

原生代码如下:

<script>

var xhr = new XMLHttpRequest();
xhr.open("GET","http://~~/users");
xhr.send(null);
xhr.onreadystatechange = function(){
    if( this.readyState === 4 ){
        console.log( this.responseText );
    }
}

</script>

若考虑兼容IE6:


        var xhr = null;
    window.XMLHttpRequest ? xhr = new XMLHttpRequest : xhr = new ActiveObject( "Microsoft.XMLHTTP" );   

若是POST方法,则须要设置请求头:

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

对应xhr.send("name=Kevin&sex=male&age=10");

xhr.setRequestHeader("Content-Type","application/json");

对应xhr.send("json格式字符串");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Josh Z.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值