简体   繁体   中英

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.

I want to get a string from the PHP file and use it in jQuery. In the example below, I want the browser to create a pop-up, with the text "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

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.

Instead I would use an AJAX request such as http://api.jquery.com/jquery.get/

For this you will need to include jQuery in your <head>

You should get the php data before html initiates, like below

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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