[英]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.我有一个从文本文件加载 JSON 对象字符串的 php 页面。 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.
我想将对象字符串发送到外部 javascript 文件,该文件最终将使用它来更新从 php 页面显示的 html。 Unfortunately I've had trouble getting the string to the external javascript.
不幸的是,我在将字符串获取到外部 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我一直在尝试遵循 Afzal Ahmad 在此处将Php 数组传递到外部 Javascript 文件中概述的方法,但没有得到任何结果
The php: 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: javascript:
console.log(userObj);
Your loadUserData function isn't returning anything.您的 loadUserData 函数没有返回任何内容。
You should remove the echo $userString;
您应该删除
echo $userString;
and add a return $user
after the file_get_contents.并在 file_get_contents 之后添加一个
return $user
。
And you should change the loadUserData();
你应该改变
loadUserData();
to $user = loadUserData();
到
$user = loadUserData();
That happens because you haven't declared $user
in the function loadUserData
as a global variable .发生这种情况是因为您没有在函数
loadUserData
中将$user
声明为全局变量。
To fix the issue, you'll have to use the global
keyword:要解决此问题,您必须使用
global
关键字:
function loadUserData() {
global $user;
$userString = 'userdata/'.$_SESSION['email'].'.txt';
echo $userString;
$user = file_get_contents($userString);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.