Ajax是什么
AJAX = Asynchronous JavaScript and XML
ajax即为js通过异步的方式向服务器发送请求并获得响应,从而局部更新网页,提高用户体验。
注意,AJAX只能向同源网址(协议、域名、端口都相同)发出HTTP请求,如果发出跨源请求,就会报错。
具体来说,AJAX包括以下几个步骤。
- 创建AJAX对象
- 发出HTTP请求
- 接收服务器传回的数据
- 更新网页数据
写法
发送Get请求
var req=new XMLHttpRequest()
req.onreadystatechange=function(){
if (ajax.readyState == 4) {
if ((ajax.status >= 200 && ajax.status < 300)|| (ajax.status == 304) ){
alert(req.responseText)
}
}
}
req.open("get","http://www.example.com/somepage.php?id=" + encodeURIComponent(id))
req.send(null)
// 或者可以这样写
req.open("get","http://www.example.com/somepage.php")
req.send('id=' + encodeURIComponent(id))
上面代码中,GET请求的参数,可以作为查询字符串附加在URL后面,也可以作为send方法的参数。
发送POST请求
var req=new XMLHttpRequest()
req.onreadystatechange=function(){
if (ajax.readyState == 4) {
if ((ajax.status >= 200 && ajax.status < 300)|| (ajax.status == 304) ){
alert(req.responseText)
}
}
}
var data = 'email='
+ encodeURIComponent(email)
+ '&password='
+ encodeURIComponent(password);
ajax.open('POST', 'http://www.example.com/somepage.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send(data);