简体   繁体   English

使用 XMLHttpRequest 的 AJAX 请求返回 PHP 文件的内容而不是执行它

[英]AJAX request using XMLHttpRequest returns content of PHP file instead of executing it

I want to execute a PHP script on a Linux server running node.js by using a call to XMLHttpRequest on the client.我想通过调用客户端上的 XMLHttpRequest 在运行 node.js 的 Linux 服务器上执行 PHP 脚本。 Instead of executing the PHP script on the server, the script contents are returned.不是在服务器上执行 PHP 脚本,而是返回脚本内容。 Is there a node.js configuration change required for the PHP script to be executed on the server?要在服务器上执行 PHP 脚本,是否需要更改 node.js 配置? Also, since node.js is used for server side javascript, can I execute a javascript file, instead of a PHP file using XMLHttpRequest?另外,由于 node.js 用于服务器端 javascript,我可以执行 javascript 文件,而不是使用 XMLHttpRequest 的 PHP 文件吗?

The goal is just to execute the script on the server just to do a simple task.目标只是在服务器上执行脚本只是为了完成一个简单的任务。 At this time, I don't need anything returned to the client.此时,我不需要任何东西返回给客户端。

Client Side:客户端:

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("mailDiv").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open("GET","phpfile.php",true);
xmlhttp.send();

Server side - PHP script phpfile.php服务器端 - PHP 脚本 phpfile.php

<?php
$to = "first.last@company.com";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body)) {
    echo("<p>Email successfully sent!</p>");
} else {
    echo("<p>Email delivery failed…</p>");
}
?>

Node.js and PHP are entirely different beasts. Node.js 和 PHP 是完全不同的野兽。 By default, node cannot execute PHP and will simply send the contents of the file to the client.默认情况下,node 无法执行 PHP,只会将文件内容发送到客户端。

You can try something like node-php-server to execute PHP within node, but I think that your best bet is to just install Apache or nginx and use it to execute PHP.您可以尝试使用node-php-server在 node 中执行 PHP,但我认为最好的办法是安装 Apache 或 nginx 并使用它来执行 PHP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM