为什么我的ajax不起作用

时间:2012-02-05 06:45:28

标签: ajax

当用户点击提交按钮时,它应该显示172-ajax-include.php。但它不起作用。我想我做得对。无法弄清楚我做错了什么。

<html>
<head>
    <script type="text/javascript">
    function load()
    { /* start function load */
        if (window.XMLHttpRequest)
        { /* 1 if start */

       xmlhttp = new XMLHttpRequest();

        } /* 1 if end */
        else
        {  /* 1 else start */  
         xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');   
        } /* 1 else end */

        xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200 /* the 200  makes sure that it's not empty*/)
        { /* 2 if start */
            document.getElementById('adiv'),innerHTML =  xmlhttp.responseText;
        } /* 2 if end */

        xmlhttp.open('GET', '172-ajax-include.php', true);
        xmlhttp.send();
        }



    } /* end function load */
    </script>

</head>
<body>

    <input type="submit" onclick="load();">
    <div id="adiv"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

open()和send()必须放在onreadystatechange处理程序之外。

 xmlhttp.onreadystatechange = function() 
    {
      if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        { /* 2 if start */
            document.getElementById('adiv'),innerHTML =  xmlhttp.responseText;
        } /* 2 if end */
     };
   xmlhttp.open('GET', '172-ajax-include.php', true);
   xmlhttp.send();

编辑:

更改html按钮

<input type"button" onclick="load()" value="Show"/>