简体   繁体   中英

How to pass data JSON string from PHP to external javascript

I have a php page that loads a JSON object string from a text file. I want to send the object string to an external javascript file which will eventually use it to update html displayed from the php page. Unfortunately I've had trouble getting the string to the external javascript.

I've been trying to follow the approach outlined by Afzal Ahmad here Pass Php Arrays to External Javascript File but I get no results

The php:

<?php

session_start();
echo 'Hello ' . $_SESSION['first'] . '<br>';
loadUserData();
displayPage();

function loadUserData(){
        $userString = 'userdata/'.$_SESSION['email'].'.txt';
    echo $userString;
    $user = file_get_contents($userString);
}

function displayPage(){
/*html stuff here*/
}

?>
<script type="text/javascript">var userObj = <?php echo json_encode($user); ?>;</script>
<script type="text/javascript" src="scripts/index.js"></script>

The javascript:

console.log(userObj);

Your loadUserData function isn't returning anything.

You should remove the echo $userString; and add a return $user after the file_get_contents.

And you should change the loadUserData(); to $user = loadUserData();

That happens because you haven't declared $user in the function loadUserData as a global variable .

To fix the issue, you'll have to use the global keyword:

function loadUserData() {
    global $user;

    $userString = 'userdata/'.$_SESSION['email'].'.txt';
    echo $userString;
    $user = file_get_contents($userString);
}

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