简单的ajax没有任何反应

时间:2013-08-19 20:58:09

标签: javascript html ajax

我尝试创建一个小的ajax脚本,将一些文本添加到div中。 什么都没发生,它杀了我。

请帮忙。

HTML:

    <!DOCTYPE>
    <html>

    <head>
                <script  type="text/javascript" src="ajax.js"></script>
                <script  type="text/javascript" src="jquery.js"></script>   
    </head>

    <body onload="process()">
        OK, you made it this far
        <br/>
        <div id="theD">
        </div>

    </body>

    </html>

ajax.js:

    var xmlHttp= createXmlHttpRequestObject();

    function createXmlHttpRequestObject(){
        var xmlHttp;

        if (window.XMLHttpRequest)(
            xmlHttp = new XMLHttpRequest();
        )else{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
        }

        return xmlHttp;
    }


    function process(){
        alert('hi');

        if (xmlHttp){
            try{
                xmlHttp.open("GET", "ajax.txt", true);
                xmlHttp.onreadystatechange = handleServerResponse;
                xmlHttp.send(null);

            }catch(e){
                alert(e.toString());

            }
        }
    }

    function handleServerResponse(){
        theD = documet.getElementById('theD');

        if (xmlHttp.readyState==1){
            theD.innerHTML += "Status1:server connection established <br/>";

        }else if (xmlHttp.readyState==4){
            if (xmlHttp.status=200){
                try{
                    text=xmlHttp.responseText
                    theD.innerHTML += "Status4:request finish<br/>";
                    theD.innerHTML += text;
            }catch(e){
                alert(e.toString);

            }

            }else{
                alert((xmlHttp.statusText);
            }
        }

    }

ajax.txt包含一个简单的字符串。

1 个答案:

答案 0 :(得分:1)

这是xhr2,如果你想要更多的浏览器支持,你可以扩展它。

http://caniuse.com/xhr2

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax</title>
<script>
function ajax(a,b,c){ // Url, Callback, just a placeholder
 c=new XMLHttpRequest;
 c.open('GET',a);
 c.onload=b;
 c.send()
}
function h(){
 document.getElementById('theD').innerText=this.response
}
window.onload=function(){
ajax('ajax.txt',h);
}
</script>
</head>
<body>
<div id="theD"></div>
</body>
</html>

如果您对此如何运作或如何扩展它有任何疑问,请询问

这里有更多关于此内容的信息

https://stackoverflow.com/a/18309057/2450730

你可以添加ie支持

替换

c=new XMLHttpRequest;

c=new XMLHttpRequest||new ActiveXObject("MSXML2.XMLHTTP.3.0");

并使用onreadystatechange

相关问题