XmlHttpRequest 使用

1. IE7以后对xmlHttpRequest 对象的创建在不同浏览器上是兼容的。下面的方法是考虑兼容性的,实际项目中一般使用Jquery的ajax请求,可以不考虑兼容性问题。

function getHttpObject() {
var xhr=false;
if (windows.XMLHttpRequest)
    xhr=new XMLHttpRequest();
else if (window.ActiveXObject)
{
    xhr=new ActiveXObject("Microsoft.XMLHttp");
}
return xhr;
}

2. XMLHttpRequest的属性及方法

属性 描述
onreadystatechange 每个状态改变都会触发,通常会调用一个javascript函数
readyState 请求的状态,5个值; 0:为初始化,1:正在加载;2:已经加载,3:交互中,4:完成
responseText 服务器的响应,表示为字符串
responseXML 服务器的响应,表示为XML,可以解析为DOM对象
status 服务器的HTTP状态码(200:ok,304:not modified,404:Not Found 等)
statusText Http状态码的相应文本(ok或Not Found)

 

方法 描述
abort() 停止当前请求
getAllResponseHeaders() 把HTTP请求的所有响应首部作为键/值对返回
getResponseHeader(“header”) 返回指定键的首部串值
open(“method”,”url”) 建立对服务器的调用,Method可以是GET,POST或PUT,URL可以是相对或绝对URL
send(content) 向服务器发送请求
setRequestHeader(“header”,”value”) 把指定首部设置为所提供的值。在设置任何首部之前必须调用open()

 

手写一个Ajax请求的例子:

$(function(){
      $("#id").onclick(tunction(){
          var request=new XMLHttpRequest();
          var url="http://www.baidu.com";
          var method="GET";    
          request.open(method,url);
          request.send(null);
          request.onreadystatechange=function(){
             if (request.readyState==4&&(request.status==200 || request.status==304))
                alert (request.reponseText);
                //如果返回的是html 标签,则可以使用
                //$(“#id2”).innerHtml=request.reponseText;
                //如果返回的xml格式,则需要将结果通过getElementByTagName(“”)[index]解析
                //alert(request.reponseXML.getElementByTagName(“”)[index])
          }
       })
})

这里再插入一下window.onload 和$(function(){})($(document).ready(function(){}))的区别:

1. window.onload 必须等到页面内包括图片的所有元素加载完毕才能执行

    $(function(){}) 是DOM结构绘制完毕后就执行,不必等到加载完毕。

2. 编写个数不同

    window.onload 不能同时编写多个,如果有多个window.onload方法,只会执行一个

    $(function(){}) 可以同时编写多个,并且都会得到执行

3. 简化写法

    window.onload 没有简写方法,但可以使用$(window).load(function(){})代替

    $(function(){})实际是$(document).ready(function(){})的缩写方法

$(window).load(function(){})一般情况下都会在$(function(){})之后执行,但是如果使用了Iframe的话

可能不一样,附上jquery 1.8.2的源码,IE只有在不是frame的情况下才和其他浏览器一样,先执行$(function(){})

对于嵌入frame中的页面,是绑定到 load 事件中,因此会先执行load 事件。

jQuery.ready.promise = function( obj ) {
    if ( !readyList ) {

        readyList = jQuery.Deferred();

        // Catch cases where $(document).ready() is called after the browser event has already occurred.
        // we once tried to use readyState "interactive" here, but it caused issues like the one
        // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready, 1 );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", jQuery.ready, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", DOMContentLoaded );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", jQuery.ready );

            // If IE and not a frame
            // continually check to see if the document is ready
            var top = false;

            try {
                top = window.frameElement == null && document.documentElement;
            } catch(e) {}

            if ( top && top.doScroll ) {
                (function doScrollCheck() {
                    if ( !jQuery.isReady ) {

                        try {
                            // Use the trick by Diego Perini
                            // http://javascript.nwbox.com/IEContentLoaded/
                            top.doScroll("left");
                        } catch(e) {
                            return setTimeout( doScrollCheck, 50 );
                        }

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
posted @ 2016-04-19 21:15  一地繁华  阅读(999)  评论(0编辑  收藏  举报