将javascript插入php文件(反之亦然)

时间:2015-04-13 12:09:48

标签: javascript php client server

我有一个用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文件中,它不会起作用。

1 个答案:

答案 0 :(得分:0)

我们没有针对这种特殊情况的所有嵌入式脚本。但通常你可以将HTML,CSS,PHP和JavaScript放在同一个文件中。该文件必须以&#39; .php&#39;结尾。必须安装PHP(&#34; test.php&#34;):

<!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>

应输出&#34; foobar&#34;。