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格式字符串");