【问题标题】:php won't run when called from a javascript file从 javascript 文件调用时,php 不会运行
【发布时间】:2017-09-16 11:12:34
【问题描述】:

我正在尝试使用 XmlHttpRequest 从 javascript 文件运行 php 脚本。但由于某种原因,我的代码只是将 php 代码作为字符串返回,而不是实际运行它。

如果我从全局 url 单独运行 php,它运行得非常好,但它不会从 javascript 文件运行,这意味着我的 javascript 请求有问题?

我使用 Apache 和 nodejs 在 Ubuntu 上本地运行所有内容。我之前被引导到这个链接:PHP code is not being executed, instead code shows on the page,但似乎 Ubuntu 没有 httpd.conf 文件,而是使用 apache2.conf。我不确定有什么区别或者如何在不破坏它的情况下弄乱它。另外,上面的链接不只是暗示这是php的错吗?但是当通过全局 url 访问时,我的 php 文件运行良好。

这是应该调用php文件的javascript的sn-p:

function drawOutput(responseText) {
    console.log(responseText);
}
function drawError(status) {
    console.log('Error: ' + status);
}
// handles the response, adds the html
function getRequest(url, success, error) {
    var req = false;
    try{
        // most browsers
        req = new XMLHttpRequest();
    } catch (e){
        console.log("XML request failed.");
        return false;
    }
    if (!req) return false;
    if (typeof success != 'function') success = function () {};
    if (typeof error!= 'function') error = function () {};
    req.onreadystatechange = function(){
        if(req.readyState == 4) {
            return req.status === 200 ? success(req.responseText) : error(req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}
var urlString = '../tests/server_scripts/page_load.php' + encodeURIComponent('game_id') + '=0&' + encodeURIComponent('client_timestamp') + '=10';

//var urlString = "http://rpal.cs.cornell.edu/YH/public/tests/server_scripts/page_load.php?" + encodeURIComponent('game_id') + '=0&' + encodeURIComponent('client_timestamp') + '=10';
//var urlString = 'http://localhost/YH/WebHanabi/public/tests/server_scripts/page_load.php&' + encodeURIComponent('game_id') + '=0&' + encodeURIComponent('client_timestamp') + '=10';
console.log(urlString);
var urlRequest = getRequest(
    urlString, // URL for the PHP file 
    drawOutput,  // handle successful request 
    drawError    // handle error
);

编辑: 这是我的 HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Hanabi Lobby</title>
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
    <script src="/js/classList.js"></script>
    <script src="/js/socket.io.js"></script>
    <script src="/js/bokeh.js"></script>
    <script src="/js/lobby.js"></script>
</head>
<body>
    <div id="header">Hanabi Lobby<hr></div>
    <div id="body">
        <div id="info-row">
            <ul>
                <li><span class="info-title">Name:</span><span class="editable" title="Click to edit"><span class="name editable-text">My Name</span><i class="fa fa-edit edit"></i></span></li>
                <li><span class="info-title">Room:</span><span class="room">My Room</span></li>
            </ul>
        </div>
        <div id="content">
            <div class="column">
                <div class="column-title">Rooms</div>
                <div class="column-container rooms">
                    <ul class="room-list">
                        <li class="joinable" x-room="room 1">room 1</li>
                        <li class="joinable" x-room="room 2">room 2</li>
                        <li class="selected-room" x-room="room 3">room 3</li>
                        <li class="joinable" x-room="room 4">room 4</li>
                    </ul>
                    <ul class="bottom-buttons">
                        <li id="new-room-button"><i class="fa fa-plus-circle" style="position: absolute; left: 10px; bottom: 5px;"></i> New Room</li>
                    </ul>
                </div>
            </div>
            <div class="column">
                <div class="column-title">Participants</div>
                <div class="column-container participants">
                    <ul class="clients-list">
                        <li class="ready">person 1</li>
                        <li class="not-ready">person 2</li>
                        <li class="ready">person 4</li>
                    </ul>
                    <ul class="bottom-buttons">
                        <li id="ready-button"><i class="icon fa fa-play-circle" style="position: absolute; left: 10px; bottom: 5px;"></i><span class="text">Ready</span></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <div id="footer">Sweet game bro!</div>
</body>
</html>

这是我试图从 javascript 运行的 PHP 文件:

<?php
header('Access-Control-Allow-Origin: *');
include("connection.php");
//specific
if(!isset($_GET["game_id"]) || !isset($_GET["client_timestamp"])){
        print(json_encode(array("error_code" => "1", "message" => "missing game_id or client_timestamp")));
    return;
}
$game_id = $_GET["game_id"];
$client_timestamp = $_GET["client_timestamp"];
if(!is_numeric($game_id) || !is_numeric($client_timestamp)){
    print(json_encode(array("error_code" => "2", "message" => "game_id or client_timestamp malformed, integers only")));
    return;
}

// jsonp
$jsonp = false;
if (isset($_GET["callback"])) {
    $jsonp = true;
    $jsonp_methodname = $_GET["callback"];
}

//insert new id
$user_id = isset($_GET["user_id"]) ? $_GET["user_id"] : generateRandomString(40);
if(!isset($_GET["user_id"])){
    $st1 = $mysqli->prepare("INSERT INTO users (user_id, user_info) VALUES (?, ?)");
    $user_info = isset($_GET["user_info"]) ? $_GET["user_info"] : "";
    $st1->bind_param("ss", $user_id, $user_info);
    $st1->execute();
}
$st = $mysqli->prepare("INSERT INTO player_pageload_log (user_id, server_timestamp, game_id, version_id, session_id, client_timestamp, host_domain, referrer_host, referrer_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$server_timestamp = time();
$version_id = isset($_GET["version_id"]) ? $_GET["version_id"] : 1;
$session_id = isset($_GET["session_id"]) ? $_GET["session_id"] : generateRandomString(36);
$host_domain = $_SERVER["HTTP_HOST"];
$referrer_host = $_SERVER["HTTP_USER_AGENT"];
$referrer_ip = $_SERVER["REMOTE_ADDR"];
$st->bind_param('siiisisss', $user_id, $server_timestamp, $game_id, $version_id, $session_id, $client_timestamp, $host_domain, $referrer_host, $referrer_ip);
$st->execute();

// Return response as either json or jsonp if method wrapper (as GET param 'callback') was specified.
$json_response = json_encode(array("error_code" => "0", "message" => "success", "user_id" => $user_id, "session_id" => $session_id));
if ($jsonp) {
    print($jsonp_methodname . '(' . $json_response . ');');
}
else {
    print($json_response);
}
?>

【问题讨论】:

  • 你是从文件系统运行脚本还是从服务器运行脚本,类似于file:///var/www/html/index.html
  • 如果不是file:///,而是http://localhost,那么看看你的js控制台。
  • 查看您之前的另一个问题stackoverflow.com/q/43421794/1415724,您声明您尝试过//InsertAbsolutePathHere/tests/my_file.phpfile:///InsertAbsolutePathHere/tests/my_file.php - 尽管您过去的所有问题都很清楚。
  • 你有 COORS 访问那个 PHP 页面吗?
  • @Fred-ii-,您是指上面代码中我的变量 urlString 的值吗?你可以看到我尝试过的所有方法。似乎以 http 开头的两个最终都给了我一个错误“No Access-Control-Allow-Origin header”,所以我希望通过使用带有“.../tests/page_load. php",但这是将文本转储到我的控制台的那个。

标签: javascript php apache xmlhttprequest


【解决方案1】:

我假设 javascript 文件在本地运行?

那么问题是因为PHP需要通过apache和PHP引擎运行才能显示出来。您的代码实际上在做的是去后端,打开一个扩展名为 .php 的文件并读取该文件。尝试使用 URL,而不是使用绝对文件路径。

【讨论】:

  • 通过 url,你的意思是像 "var urlString = "rpal.cs.cornell.edu/YH/public/tests..." (整个东西太长了,不能放在这里)?
  • 当然可以。但是你需要在前面加上“http://”。事情是这样的,PHP 只是纯文本。它不是像编译文件那样的 shell 代码。您不能执行原始 PHP。它必须通过解释器运行。 Apache 配置为在用户访问 .php 文件时使用 PHP 解释器。在 apache 之外,如果你只是想抓取文件并阅读它,你最终会这样做:阅读它。另一种方法是执行 shell 命令“php myphpfile.php”
  • 对不起,我不太明白那个解释。我对后端和一切都很陌生。我不完全确定 Apache 是如何工作的。我所知道的是,在某个地方有一组文件共同组成了这个 Apache,没有它,php 就无法运行。但是为什么当我在浏览器中打开文件时php会正常运行,而当我从javascript调用它时却不能?是不是因为我调用它的文件以.js而不是.php开头,所以Apache找不到它?
  • PHP 只是一个文本文件,你可以用记事本阅读。它不是可执行代码。当您像现在一样打开它时,它与在文本编辑器中打开它没有什么不同。 PHP 需要通过所谓的“解释器”运行。它的作用是将PHP 代码在运行时 转换为可执行代码。了解这一点很重要。 PHP 在通过解释器运行之前是不可执行的。 Apache 知道使用哪个解释器。如果你正在绕过你正在做的 apache,那么你的 PHP 只是磨坊文本文件的痛苦运行。
  • 谢谢!所以现在我得到一个“请求的资源上没有'Access-Control-Allow-Origin'标头”。你会碰巧知道如何解决这个问题吗?我假设这意味着我需要 php 文件中的 CORS 标头,但你可以看到我在哪里尝试过,它仍然给我同样的错误。
猜你喜欢
  • 2015-03-20
  • 2012-11-05
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2012-04-23
  • 2016-06-29
  • 2021-12-24
  • 2020-08-13
相关资源
最近更新 更多