Ajax不会在网页上显示

时间:2014-04-25 14:17:36

标签: javascript php ajax

我目前正在尝试使用JavaScript和PHP文件在netbeans中使用Ajax。下面的代码我应该点击按钮,php填充的内容应该出现,但事实并非如此。当我在firefox中使用firebug时,响应显示完整的php文件已经返回但不会显示在网页上。为什么???

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <script>
            function getXMLHttp() {
                var xmlHttp

                try {
                    //Firefox, Opera 8.0+, Safari
                    xmlHttp = new XMLHttpRequest();
                }
                catch (e) {
                    //Internet Explorer
                    try {
                        xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                    }
                    catch (e) {
                        try {
                            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        catch (e) {
                            alert("Your browser does not support AJAX!")
                            return false;
                        }
                    }
                }
                return xmlHttp;
            }


            function MakeRequest() {
                var xmlHttp = getXMLHttp();

                xmlHttp.onreadystatechange = function() {
                    if (xmlHttp.readyState == 4) {
                        HandleResponse(xmlHttp.responseText);
                    }
                }

                xmlHttp.open("GET", "ajax.php", true);
                xmlHttp.send(null);
            }


            function HandleResponse(response) {
                document.getElementById('ResponseDiv').innerHTML = response;
            }
        </script>    
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
        <div id='ResponseDiv'>
            This is a div to hold the response.
        </div>
    </body>
</html>

我的PHP文件是

<?php 
echo "This is a php response to your request!!!!!!";
?>

2 个答案:

答案 0 :(得分:1)

除了HTML代码不太合适之外,为什么不使用jQuery呢?

<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>

<script type="text/javascript">
    $("#get").click(function() {
        $.get( "ajax.php", function( data ) {
            $( "#result" ).html( data );
        });
    });
</script>

答案 1 :(得分:0)

PHP是服务器端,不能在客户端运行。您的回复应来自URL而不是文件的内容。确保您的响应包含HTML而非PHP,应该引导您找到解决方案。

尝试用你的PHP文件替换 <p>This is a php response to your request!!!!!!</p>

如果这样可以显示您的内容,那么您就会遇到问题和解决方案。