一、ajax简介
异步的javascript和xml
创建快速动态网页的技术
通过在后台与服务器进行少量的数据交换,不用重新加载整个页面,只需要对网页某部分进行刷新
二、XMLHttpRequest
1、是ajax的基础
2、XMLHttpRequest对象 用于在后台与服务器交换数据。这意味着可以不用重新加载整个页面,对网页的某部分进行更新。
3、
①创建XMLHttpRequest对象
var xmlhttp;
if(window.XMLHttpRequest){//如果支持XMLHttpRequest对象,则创建一个XMLHttpRequest对象
xmlhttp= new XMLHttpRequest();
}else{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");//否则创建ActiveX对象
}
②用于和服务器交换数据(所以就有请求和响应)
open(method,url,async)
method:规定请求类型
url:文件在服务器上的类型
async:同步(false)还是异步(true)
PS:
(一般大部分都是异步请求)
send(string):将请求发送到服务器 string:仅用于 POST 请求
A。get请求
<!--StartFragment --><head>
<script type="text/javascript">
function loadXMLDoc()
{
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</html>
B。post请求
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","/ajax/demo_post2.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据<button>
<div id="myDiv"></div>
</body>
<xml>
三、响应
responseXML 获得 XML 形式的响应数据。
responseText 获得字符串形式的响应数据
四、
属性:status:200--ok;404--未找到页面
readystate:0--请求未初始化
1--服务连接已建立
2--请求已接收
3--请求处理中
4--请求已完成且响应已就绪
方法:onreadystatechange()--每当readystate属性改变时都会调用这个函数