简体   繁体   English

如何在Javascript代码中访问位于外部PHP文件中的PHP变量?

[英]How to access PHP variables located in external PHP file within Javascript code?

I am a learning developer that is trying to utilize websockets, php and javascript to create a module for a web application I use. 我是一名学习型开发人员,正在尝试利用websockets,php和javascript为我使用的Web应用程序创建模块。 However, I am not sure if I can use the two languages together in such a way that I am doing as I am not very knowledgeable with Javascript yet. 但是,我不确定是否可以以我正在使用的方式同时使用这两种语言,因为我对Javascript尚不很了解。

What I would like to do is grab two strings located in a settings.php file, get those strings, convert those strings over to a Javascript string so that I can use what the PHP string value is as the Javascript variable. 我想做的是获取位于settings.php文件中的两个字符串,获取这些字符串,将这些字符串转换为Javascript字符串,以便我可以将PHP字符串值用作Javascript变量。 I tried to follow guides online and got this far with the browser console only showing 我试图按照在线指南进行操作,但到目前为止,浏览器控制台仅显示

WebSocket connection to 'wss://%3C/?php%20echo%20$server_ip%20?%3E:%3C?php%20echo%20$server_port%20?%3E/websocket' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED

Followed guides similar to this including this one to try to gain an understanding with no luck: https://www.dyn-web.com/tutorials/php-js/scalar.php 遵循与此类似的指南,包括试图通过运气获得理解的指南: https : //www.dyn-web.com/tutorials/php-js/scalar.php

This guide was suggested as similar, but this involves an external Javascript file and not an external PHP file. 建议该指南类似,但这涉及一个外部Javascript文件而不是一个外部PHP文件。 This is totally different. 这是完全不同的。 Access PHP var from external javascript file 从外部javascript文件访问PHP var

Here is the main code in question where I'll access the PHP variable in Javascript: 这是有问题的主要代码,我将在其中使用Javascript访问PHP变量:

    <!--Include some variables from PHP settings file to fetch IP/port-->
    <?php include(ROOT_PATH . '/modules/Webchat/includes/settings.php'); ?>
    <?php echo $server_ip; ?>

    <script type="text/javascript">
        $(document).ready(function(){
            var socket;
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }
            if (window.WebSocket) {


                var ip = "<?php echo $server_ip ?>";
                var port = "<?php echo $server_port ?>";
                // TODO: Get socketAddress from settings.php


                var socketAddress = ip + (port ? ':' + port : '');


                var nextID = 0;
                var messageCount = 0;

                socket = new WebSocket("wss://" + socketAddress + "/websocket");

Here is my settings.php file where the PHP variables are stored: 这是我的存储PHP变量的settings.php文件:

<?php
$server_ip = $queries->getWhere('mc_servers', array('is_default', '=', 1));
$server_port = 25566;
$endpoint = "/websocket";
?>

I expect the output of the server_ip php variable to be a string such as "server.example.com". 我希望server_ip php变量的输出为字符串,例如“ server.example.com”。 I expect the output of server_port to be 25566. 我期望server_port的输出为25566。

You could solve this by having the PHP file echo out the variables, then use javascript to request and load them. 您可以通过让PHP文件回显变量,然后使用javascript请求并加载它们来解决此问题。

Make sure that settings.php is accessible somewhere on the server and put 确保可以在服务器上的某个位置访问settings.php并将其放入

<?php
$server_ip = $queries->getWhere('mc_servers', array('is_default', '=', 1));
$server_port = 25566;
$endpoint = "/websocket";
header("Access-Control-Allow-Origin: *");
echo json_encode([$server_ip, $server_port, $endpoint]);
?>

The header keeps a CORS error from happening and then we encode the values as JSON. 标头可防止发生CORS错误,然后将值编码为JSON。

<script type="text/javascript">
    $(document).ready(function(){
        var socket;
        if (!window.WebSocket) {
            window.WebSocket = window.MozWebSocket;
        }
        if (window.WebSocket) {
            $.getJSON('/modules/Webchat/includes/settings.php') 
              .done(function setvars(data) {
                  server_ip = data[0];
                  server_port = data[1];
                  endpoint = data[2];
              })
              .fail(function (data) {
                  alert('Couldn't get server variables! ')
              });

            var socketAddress = ip + (port ? ':' + port : '');

            var nextID = 0;
            var messageCount = 0;

            socket = new WebSocket("wss://" + socketAddress + "/websocket");
</script>

What this code does is it uses $.getJSON to retrieve the encoded variables from settings.php as load then as javascript variables 该代码的作用是使用$.getJSONsettings.php检索编码的变量,然后将其作为负载,然后作为javascript变量

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

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