无法获取ajax以显示.php

时间:2014-03-01 22:15:39

标签: ajax

我正在尝试学习Ajax,但一直遇到麻烦。基本上我有httpRequest检查哪个浏览器。然后让浏览器将.php文件加载到div中。

<script>
    function getXMLHTTPRequest(){
        var ajaxRequest = false;

        try{
            ajaxRequest = new XMLHttpRequest();
        } catch (e)
        {
            try
            {
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            }catch (e){
                try{
                    new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        var ajaxRequest = getXMLHTTPRequest();
        ajaxRequest.open("GET","ajaxNewbie.php");

        ajaxRequest.onreadystatechange = function ()
        {

            if(ajaxRequest.readyState === 4)
            {
                //get the data from the server's response
            document.greetingInfo.innerHTML = ajaxRequest.responseText;
            } else {
            window.alert("readyState = " + ajaxRequest.readyState);
            }
        }       
    }
    </script>
</head>
<body onload="ajaxRequest.send(null);">
    <div id="greetinginfo">
    </div>
</body>

1 个答案:

答案 0 :(得分:0)

你犯了一些错误:

  1. getXMLHTTPRequest函数未完成,因此将自行调用
  2. 你忘记了ajaxRequest.send();
  3. 考虑以下示例: http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_get