duanchi0897 2017-04-20 02:10
浏览 50
已采纳

从javascript文件调用时,php不会运行

I'm trying to use XmlHttpRequest to run a php script from a javascript file. But for some reason, my code is only returning the php code as a string instead of actually running it.

The php runs perfectly fine if I run it alone from a global url, but it won't run from the javascript file, implying there's something wrong with my javascript request?

I'm running everything locally on Ubuntu with Apache and nodejs. I was directed to this link earlier: PHP code is not being executed, instead code shows on the page, but it seems Ubuntu does not have an httpd.conf file and uses an apache2.conf instead. I'm not sure what the difference is or how to mess with it without breaking it. Also, doesn't the above link only imply that it's php's fault? But my php file runs perfectly fine when accessed through a global url.

Here's the snippet of javascript that's supposed to call the php file:

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
);

Edit: Here's my 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>

And here's the PHP file I'm trying to run from the javascript:

<?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);
}
?>
  • 写回答

1条回答 默认 最新

  • douwen3965 2017-04-20 02:19
    关注

    I'm assumning the javascript file is running locally?

    Then the problem is because PHP needs to run through apache and the PHP engine before you can display it. What your code is actually doing is going to the backend, opening a file with the .php extension and reading that file. Instead of using an absolute file path, try using a URL.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程