什么可能导致 JavaScript 代码无法在 process.php 文件中执行,以及如何解决此问题?

问题描述 投票:0回答:1

描述:我正在开发一个 PHP 脚本,该脚本应该使用 JavaScript 自动单击电子邮件链接。该代码在单独的 test.php 文件中运行良好,但在 process.php 中,JavaScript 不执行。下面是相关代码:

<?php
include_once 'libs/load.php';
if (isset($_POST['command'])) {
    $command = trim($_POST['command']);
    handleCommand($command);
}

function handleCommand($command)
{
    switch ($command) {
        case 'email':
            $email = "[email protected]";
            echo "<html><body>";
            echo "<a id=\"emailLink\" href=\"mailto:$email\" style=\"color: rgb(5, 206, 145);\">$email</a>";
            echo "<script type=\"text/javascript\">
                    document.addEventListener('DOMContentLoaded', function() {
                        console.log('JavaScript is running');
                        alert('JavaScript is running');
                        document.getElementById('emailLink').click();
                    });
                  </script>";
            echo "</body></html>";
            break;
        default:
            echo "---\n";
            echo "Unknown command: $command\n";
            echo "---";
            break;
    }
}
?>    
javascript php html error-handling
1个回答
0
投票

抱歉,这是我的错误,评论被发送到 process.php,它给出了响应。然后将响应转换为文本以在文档中打印结果。所以, 我改了代码

fetch('process.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'command=' + encodeURIComponent(command)
        })
        .then(response => response.text())
        .then(data => {
            if (data.trim() === 'OPEN_MAILBOX') {
                console.log("Opening mailbox...");
                window.location.href = 'mailto:[email protected]';
            }
            else
            {
                output.innerHTML += '<div class="command-output">' + data.replace(/\n/g, '<br>') + '</div>';
            }
<?php
include_once 'libs/load.php';
if (isset($_POST['command'])) {
    $command = trim($_POST['command']);
    handleCommand($command);
}

function handleCommand($command)
{
    switch ($command) {
        case 'email':
            echo "OPEN_MAILBOX";
            break;
        default:
            echo "---\n";
            echo "Unknown command: $command\n";
            echo "---";
            break;
    }
}
?>

总结: 此代码使用命令向 process.php 发送 POST 请求。根据服务器的响应,它会打开默认电子邮件客户端或在网页上显示响应数据。如果响应是“OPEN_MAILBOX”,则触发电子邮件客户端;否则,它会在输出元素中显示响应。

© www.soinside.com 2019 - 2024. All rights reserved.