【问题标题】:Insert javascript into php file (or vice versa)将javascript插入php文件(反之亦然)
【发布时间】:2015-04-13 12:09:48
【问题描述】:

我有一个用 php 编写的服务器文件和一个客户端 html 文件(主要是 javascript),我希望将两者都放入一个文件中并且仍然可以通信。我尝试在客户端代码上方复制服务器的 php 代码,但没有成功。原来是这样的:

  <!doctype html>
<html>




    <meta charset='UTF-8' />
    <style>
        input, textarea {border:1px solid #CCC;margin:0px;padding:0px}
        #body {max-width:800px;margin:auto}
        #log {width:100%;height:400px}
        #message {width:100%;line-height:20px}
    </style>


    <?php

// prevent the server from timing out

set_time_limit(0);



// include the web sockets server script (the server is started at the far bottom of this file)

require 'class.PHPWebSocket.php';



// when a client sends data to the server

function wsOnMessage($clientID, $message, $messageLength, $binary) {

    global $Server;

    $ip = long2ip( $Server->wsClients[$clientID][6] );



    // check if message length is 0

    if ($messageLength == 0) {

        $Server->wsClose($clientID);

        return;

    }

$x = 0;

    //The speaker is the only person in the room. Don't let them feel lonely.



for ($i=1; $i <= 10; $i++) {



$q=".68.111.160";

$string =100+$i*10;

$string .= $q;

$Server->wsSend($clientID, $string);



    sleep (3);

}





}



// when a client connects

function wsOnOpen($clientID)

{

    global $Server;

    $ip = long2ip( $Server->wsClients[$clientID][6] );



    $Server->log( "$ip ($clientID) has connected." );



    //Send a join notice to everyone but the person who joined

    foreach ( $Server->wsClients as $id => $client )

        if ( $id != $clientID )

            $Server->wsSend($id, "Visitor $clientID ($ip) has joined the room.");

}



// when a client closes or lost connection

function wsOnClose($clientID, $status) {

    global $Server;

    $ip = long2ip( $Server->wsClients[$clientID][6] );



    $Server->log( "$ip ($clientID) has disconnected." );



    //Send a user left notice to everyone in the room

    foreach ( $Server->wsClients as $id => $client )

        $Server->wsSend($id, "Visitor $clientID ($ip) has left the room.");

}



// start the server

$Server = new PHPWebSocket();

$Server->bind('message', 'wsOnMessage');

$Server->bind('open', 'wsOnOpen');

$Server->bind('close', 'wsOnClose');

// for other computers to connect, you will probably need to change this to your LAN IP or external IP,

// alternatively use: gethostbyaddr(gethostbyname($_SERVER['SERVER_NAME']))

$Server->wsStartServer('127.0.0.1', 9300);



?>


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="fancywebsocket.js"></script>
    <script>
        var Server;
        function log( text ) {
            $log = $('#log');
            //Add text to log
            $log.append(($log.val()?"\n":'')+text);
            //Autoscroll
            $log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
        }
        function send( text ) {
            Server.send( 'message', text );
        }
    </script>
 <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="http://d3js.org/d3.v3.min.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script src="http://datamaps.github.io/scripts/datamaps.world.min.js?v=1"></script>
    <script src="converter.js"></script>
    <div id="container1" style="position: relative; width:900px; height: 700px;"></div>
    <script>
        var map = new Datamap({
            scope: 'world',
            element: document.getElementById('container1'),
            projection: 'mercator',
            fills: {
                lt50: 'rgba(0,244,244,0.9)',
                on: 'red',
                HIGH: '#afafaf',
                LOW: '#123456',
                MEDIUM: 'blue',
                UNKNOWN: 'rgb(50,0,0)',
                off: "#ABDDA4",
                defaultFill: "#ABDDA4"
            },
            data: {
            }
        })
        var x;
        var colors = d3.scale.category10();
        $(document).ready(function() {
            log('Connecting...');
            Server = new FancyWebSocket('ws://127.0.0.1:9300');
            $('#message').keypress(function(e) {
                if ( e.keyCode == 13 && this.value ) {
                    log( 'You: ' + this.value );
                    send( this.value );
                    $(this).val('');
                }
            });
            //Let the user know we're connected
            Server.bind('open', function() {
                log( "Connected." );
            });
            //OH NOES! Disconnection occurred.
            Server.bind('close', function( data ) {
                log( "Disconnected." );
            });
            //Log any messages sent from server
            Server.bind('message', function( payload ) {
log( payload );
                  var ip = payload;
        $.get("http://ipinfo.io/" + ip, function(response) {
            x = response.country;
        }, "jsonp");
        var interval_x = window.setInterval(function() {
            var country_name = convert[x];
            var interval_1 = window.setInterval(function() {
                var country = {}
                var country = {}
                country[country_name] = {
                    fillKey: 'on'
                }
                map.updateChoropleth(country);
            }, 2000);
            myVar = window.setTimeout(function() {
                clearInterval(interval_1);
                var country = {}
                country[country_name] = {
                    fillKey: 'off'
                }
                map.updateChoropleth(country);
            }, 4000);
        }, 4000);
            });
            Server.connect();
        });
//---------------------------------------IP  Goes Here------------------------------------------------
    </script>
<body>
    <div id='body'>
        <textarea id='log' name='log' readonly='readonly'></textarea><br/>
        <input type='text' id='message' name='message' />
    </div>
</body>
</html>

但它不会工作,知道这是放在一个 html 文件中。

【问题讨论】:

  • PHP 不在 html 文件中执行。
  • @Daan 那我该怎么办?
  • 如果您希望 php 执行将 .html 更改为 .php。请注意,需要在您的服务器上安装 php。

标签: javascript php client server


【解决方案1】:

我们没有针对这种特殊情况的所有嵌入式脚本。但通常您可以将 HTML、CSS、PHP 和 JavaScript 放在同一个文件中。该文件必须以'.php'结尾并且必须安装PHP(“test.php”):

<!doctype html>
<html><head>

    <title>Test</title>

</head><body>

    <div id="test">
        <?php echo 'foobar'; ?>
    </div>

    <script>
        alert(document.getElementById('test').innerHTML);
    </script>

</body></html>

应该输出“foobar”。

【讨论】:

  • 所以整个代码应该放在一个php文件中吧?如果是这样,你如何通过浏览器运行 php 文件?
  • 只需导航到地址栏中的文件:例如localhost/test.php
  • 谢谢,我已经这样做了,但它只是在对话框中显示 php 代码然后我按确定它只是显示客户端(javascript)
  • 那么您的本地 Web 服务器上没有正确安装 PHP。按照php.net上的说明进行操作
  • 我已经运行了你的代码并且它可以工作,然后我对我的代码做了同样的事情,我收到了这个错误localhost/test.php [HTTP/1.0 500 Internal Server Error 6ms]
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 2012-06-27
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
相关资源
最近更新 更多