AJAX基础!

时间:2014-05-09 03:16:17   收藏:0   阅读:325

异步js和xml,页面不整个刷新的情况下发送http请求和处理回应

原理

XMLHttpRequest对象,是一个js对象

在高级浏览器,直接new XMLHttpRequest创建,在老版本的IE上用ActiveX对象创建new ActiveXObject("Microsoft.XMLHTTP")

发送请求的方法

方法 
描述

open(method,url,async)

规定请求的类型、URL 以及是否异步处理请求。

send(string)

将请求发送到服务器。

方法 
描述

setRequestHeader(header,value)

向请求添加 HTTP 头。

像表单一样提交数据

xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
getAllResponseHeaders()
DOMString getAllResponseHeaders();

Returns all the response headers as a string, or null if no response has been received. Note: For multipart requests, this returns the headers from the current part of the request, not from the original channel.

getResponseHeader()
DOMString? getResponseHeader(DOMString header);

Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn‘t exist in the response.

Async=true
需要提前设置响应函数
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
Async=false
直接放在send方法之后处理响应
xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
服务器响应

属性 
描述

responseText 
获得字符串形式的响应数据。

responseXML 
获得 XML 形式的响应数据。

属性 
描述

onreadystatechange 
存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

readyState

存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

status

200: "OK"

404: 未找到页面

AJAX基础!,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!