---
title: "从一个简单的例子看ajax的执行过程"
author: "icyheart"
date: "2009-11-11T10:18:40Z"
tags: ["Ajax", "HTML", "JavaScript", "Microsoft"]
slug: "ajax"
draft: false
lastmod: "2009-11-11T10:46:57Z"
id: 514166
url: "https://sucre.iteye.com/blog/514166"
---

这个例子虽然简单，但是可以通过debug模式来仔细研究一下ajax在执行过程中的执行顺序，页面加载时会先去执行handleStateChange(),但是执行的时候不会进到方法内，当点击按钮执行到xmlHttp.onreadystatechange = handleStateChange;时，程序 不会去执行handleStateChange()这个方法，执行open后才会再次进入handleStateChange()这个方法,执行send后会再次进入handleStateChange()这个方法,这个时候xmlHttp.readyState会一直往后执行，一直到状态4为止，这时数据就返回了。每当 XMLHTTP 对象的状态发生改变时，handleStateChange() 函数就会执行。

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Simple XMLHttpRequest</title>
        <script type="text/javascript">
            var xmlHttp;
            function createXMLHttpRequest(){
                if (window.ActiveXObject) {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                else 
                    if (window.XMLHttpRequest) {
                        xmlHttp = new XMLHttpRequest();
                    }
            }
            
            function startRequest(){
                createXMLHttpRequest();//创建XMLHttpRequest
                xmlHttp.onreadystatechange = handleStateChange;
                xmlHttp.open("GET", "simpleResponse.txt", true);
                xmlHttp.send(null);
            }
            
            function handleStateChange(){
                if (xmlHttp.readyState == 4) {
                    if (xmlHttp.status == 200) {
                        document.getElementById("test").innerHTML = xmlHttp.responseText;//返回simpleRespose.txt中的内容
                    }
                }
            }
        </script>
    </head>
    <body>
        <form action="#">
            <input type="button" value="Start Basic Asynchronous Request" onclick="startRequest();"/>
            <div id="test">
            </div>
        </form>
    </body>
</html>
```