简体   繁体   English

如何从外部PHP文件中获取字符串并将其设置为JavaScript中的var

[英]How to get a string from external PHP file and set it as var in JavaScript

I thought this would be simple enough, but I can't get it to work. 我认为这很简单,但我无法让它发挥作用。

I have two files. 我有两个文件。 main.html and data.php The two files are in the same folder on a server. main.htmldata.php这两个文件位于服务器上的同一文件夹中。

I want to get a string from the PHP file and use it in jQuery. 我想从PHP文件中获取一个字符串并在jQuery中使用它。 In the example below, I want the browser to create a pop-up, with the text "xxxx". 在下面的示例中,我希望浏览器创建一个弹出窗口,文本为“xxxx”。 I get no pop-up. 我没有弹出窗口。

data.php

<?php

$var = "xxxx";

echo json_encode($var);

?>

main.html

<!DOCTYPE html>
<html>    
    <head>      
        <script type="text/javascript" src="scripts/jquery-1.11.1.js"></script>
        <script>
            $(document).ready(function() {
                var testString = <?php $var = json_decode(file_get_contents('data.php'), true); echo $var; ?>;
                alert(testString);
            });
        </script>
    </head>
    <body>
        <h1>Test</h1>
    </body>
</html>

Any takers? 任何接受者?

<!DOCTYPE html>
<html>
    <head>
        <script>
            $(document).ready(function() {
                $.ajax({
                    url:"data.php",
                    success:function(result){
                        alert(result);
                    }
                });             
            });
        </script>
    </head>
    <body>
        <h1>Test</h1>
    </body>
</html>

The first problem with this is that on many servers .html is not parsed for PHP 第一个问题是在许多服务器上.html没有为PHP解析

The second problem is that the file_get_contents will actually display the full contents of your .php file (including the <?php ) which is likely not what you're looking for. 第二个问题是file_get_contents实际上会显示你的.php文件的全部内容(包括<?php ),这可能不是你想要的。

Instead I would use an AJAX request such as http://api.jquery.com/jquery.get/ 相反,我会使用一个AJAX请求,如http://api.jquery.com/jquery.get/

For this you will need to include jQuery in your <head> 为此,您需要在<head>包含jQuery

You should get the php data before html initiates, like below 您应该在html启动之前获取php数据,如下所示

<?php
$var = json_decode(file_get_contents('data.php'), true);
?>
<!DOCTYPE html>
<html>    
    <head>      
        <script>
            $(document).ready(function() {
                var testString = <?php echo $var; ?>;
                alert(testString);
            });
        </script>
    </head>
    <body>
        <h1>Test</h1>
    </body>
</html>

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

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