我的AJAX文件不起作用

时间:2012-07-13 06:26:38

标签: php javascript html ajax

我只是创建一个简单的AJAX应用程序,以便我的html页面可以通过ajax.js文件从php文件中获取一些数据,我已将它们放在服务器中,所以当我访问localhost / mypage时,它应该是执行,但似乎有一些问题,因此事情不会按照我的预期方式发生。

这是我的html文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <META http-equiv="Content-Type" Content="text/html; Charset=UTF-8">
    <title>
        My Portal
    </title>
    <link rel="stylesheet" href="style.css" type="text/css"/>
    <script type="text/javascript" src="ajax.js"></script>
</head>
<body onload="load()">
    <div id="header">
        <img src="images/logo.gif" id="logo" alt="Logo"/>
        <a href="http://www.google.com">
            <img src="images/logo2.png" id="logo2" align="right" alt="google Ltd"/>
        </a>
    </div> 
    <div id="container">
        <div id="function"></div>
        <div id="Display"></div>
        <div id="View"></div>
    </div>
    <div id="footer">
    </div>
</body>
</html>

以下是js文件:

function load(){
    var xmlhttp;
    if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
            else{ // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }               

    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById("function").innerHTML=xmlhttp.responseText;         
        }
    }

    xmlhttp.open("GET","test.php", true);
    xmlhttp.send();
}

最后是php文件:

<?php
     print "<h1>hgfkegfalhgj</h1>";
?>

我希望它应该在我的页面中打印出上面的字符串,但是,没有任何东西可以显示,有人能告诉我问题在哪里吗?我已经检查过我已经在我的浏览器中启用了javascript,所以我很确定我的html文件可以调用js文件中的函数。

3 个答案:

答案 0 :(得分:1)

我不知道PHP,但您必须将内容类型设置为text/plain。喜欢:

header('Content-Type: text/plain');

答案 1 :(得分:1)

您的代码适合我。

问题可能是以下任何一种情况:

1)检查test.php的路径(我建议在xmlhttp.open()中使用绝对路径)

2)您的服务器可能无法正确返回页面(尝试打开test.php,并检查输出)

您可以使用像firebug这样的浏览器插件来分析ajax请求和响应,它可以为您提供更好的洞察力。

答案 2 :(得分:0)

而不是body标签中的onLoad函数尝试使用

<script>
window.onload = function(){
load();
};
function load(){
//your code
}
</script>

或在body之前尝试使用脚本load()函数。我认为它会解决你的问题。 另外尝试更改id,最好不要将关键字用作id(函数id将其更改为其他内容)