0

我只是做了一个简单的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>";
?>

我希望它应该在我的页面中打印出上面的 char 字符串,但是,什么都不能显示,谁能告诉我问题出在哪里?我检查了我已经在浏览器中启用了 javascript,所以我很确定我的 html 文件可以调用 js 文件中的函数。

4

3 回答 3

1

你的代码对我有用。

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

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

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

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

于 2012-07-13T06:45:08.377 回答
1

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

header('Content-Type: text/plain');
于 2012-07-13T06:35:26.117 回答
0

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

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

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

于 2012-07-13T06:41:59.230 回答