---
title: "ajax"
author: "xiaotongeye"
date: "2016-06-13T16:12:09Z"
tags: []
categories: ["Web前端"]
slug: "ajax"
draft: false
lastmod: "2016-06-13T16:20:52Z"
id: 2304665
url: "https://xiaotongeye.iteye.com/blog/2304665"
---

**Ajax**

XMLHttpRequest 对象


```javascript

var xhr;
if(window.XMLHttpRequest){
   //code for IE7+,firfox,chrome,opera,safari
   xhr = new XMLHttpResquest();
}else {
   //code for IE6,IE5
   xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

```

向服务器发送GET请求

```javascript

xhr.open("GET","test1.php?t="+Math.random(),true);//true异步进行/false同步进行
xhr.send();

```

向服务器发送POST请求
使用setRequestHeader()来添加HTTP头，然后send()方法中规定希望发送的数据

```javascript

xhr.open("POST","test.php",true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("fname = bill&lname = gates");

```

XMLHttpRequest的三个重要属性：

1.readyState属性

readyState存有XMLHttpRequest的状态属性，从0到4发生变化。
0 请求未初始化
1 服务器连接已建立
2 请求已接收
3 请求处理中
4 请求已完成，且响应已就绪

2.onreadystatechange

每当readyState发生改变时就会触发onreadystatechange事件

3.Status

200：OK
404：未找到页面

当readyState=4并且status=200时，表示响应已就绪

```javascript

xhr.onreadystatechange = function(){
   if(this.readyState == 4 && this.status == 200){
      //执行成功
   }
}

```