【问题标题】:XAMPP - PHP script will not display in HTML fileXAMPP - PHP 脚本不会显示在 HTML 文件中
【发布时间】:2017-06-28 09:05:15
【问题描述】:

我正在运行 XAMPP 和 Apache。我有两个文件:

index.php

<html>
<head>
<title>php script</title>
</head>
<body>

<?php
header("Access-Control-Allow-Origin: *");
echo "hello world";
?>

</body>
</html>

post.html

<html>
<head>
<title>html page</title>
</head>
<body>
<script>

var xhr;
xhr=new XMLHttpRequest();
xhr.open("POST", "http://localhost/demoApp/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send();

</script>
</body>
</html>

我希望 post.html 调用 index.php 以便 post.html 在 html 页面上显示“hello world”。当我打开 index.php 时,我看到“hello world”。

我也知道 post.html 正在调用 index.php 因为我有其他脚本,当复制到 index.php 时会成功如果我打开 post.html,请给我发送电子邮件。

如果 post.html 确实在调用 index.php,为什么我的回显没有显示在 post.html 上?

【问题讨论】:

    标签: javascript xmlhttprequest


    【解决方案1】:

    post.html 正在发出请求,但您实际上并没有对该请求执行任何操作。使用 ajax 时,javascript 会进行调用,您需要明确告诉它您想对响应做什么。

    要简单地提醒远程内容,请收听onreadystatechange event,当它为 4(完成)时,显示提醒:

    xhr.onreadystatechange = function() {
        if(xhr.readyState==4) {
            alert(xhr.responseText);
        }
    }
    

    如果您希望将数据附加到任何地方(不使用 jQuery),我建议分配一个带有 ID 的 div,然后附加或分配数据:

    index.php:

    <?php
    header("Access-Control-Allow-Origin: *");
    echo "hello world";
    ?>
    

    post.html:

    <html>
    <head>
    <title>html page</title>
    </head>
    <body>
    <div id="remote_content"></div>
    <script>
    
    var xhr;
    xhr=new XMLHttpRequest();
    xhr.open("POST", "http://localhost/demoApp/index.php", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() {
        if(xhr.readyState !== 4)
            return;
    
        document.getElementById('remote_content').innerHTML = xhr.responseText;
    }
    xhr.send();
    
    </script>
    </body>
    </html>
    

    【讨论】:

    • 感谢您的帮助。在我所有的研究中,我的理解是,通过 POST 到包含 PHP 脚本的服务器,PHP 脚本将在我的 HTML 页面上执行。
    • 直接访问脚本时确实如此,而不是在 AJAX 上下文中,您需要告诉脚本如何处理您发布到的页面的输出。
    猜你喜欢
    • 2016-02-15
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-04-29
    • 2014-11-16
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多