ASP.NET MVC2 in Action 读书笔记 [12-1] Custom Ajax

<script type="text/javascript">
        function getXmlHttpRequest() {
            var xhr;
            //check for IE implementation(s)
            if (typeof ActiveXObject != 'undefined') {
                try {
                    xhr = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                }
            } else if (XMLHttpRequest) {
                //this works for Firefox, Safari, Opera    
                xhr = new XMLHttpRequest();
            } else {
                alert("Sorry, your browser doesn't support ajax");
            }

            return xhr;
        }
    
        function getMessage() {
            //get our xml http request object
            var xhr = getXmlHttpRequest();

            //prepare the request
            xhr.open("GET", "get_message.html", true)
            
            //setup the callback function
            xhr.onreadystatechange = function() {
                //readyState 4 means we're done
                if(xhr.readyState != 4) return;
                    
                //populate the page with the result
                document.getElementById('result').innerHTML = xhr.responseText;
            };
        
            //fire our request
            xhr.send(null);
        }
    </script>

<button type="button" onclick="getMessage()">Get the Message</button>
<div id="result"></div>
posted @ 2011-08-04 09:28  RobotTech  阅读(157)  评论(0编辑  收藏  举报