我有一个变量在PHP,我需要它的值在我的JavaScript代码。我怎么能把我的变量从PHP到JavaScript?
我有这样的代码:
<?php
$val = $myService->getValue(); // Makes an API and database call
在同一页上,我有JavaScript代码,需要$val变量的值作为参数传递:
<script>
myPlugin.start($val); // I tried this, but it didn't work
<?php myPlugin.start($val); ?> // This didn't work either
myPlugin.start(<?=$val?>); // This works sometimes, but sometimes it fails
</script>
我想出了一个简单的方法来分配JavaScript变量使用PHP。
它使用HTML5数据属性来存储PHP变量,然后在页面加载时分配给JavaScript。
例子:
<?php
$variable_1 = "QNimate";
$variable_2 = "QScutter";
?>
<span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
<?php
下面是JavaScript代码
var variable_1 = undefined;
var variable_2 = undefined;
window.onload = function(){
variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
}
myPlugin.start($val); // Tried this, didn't work
它不起作用,因为就JavaScript而言,$val是未定义的,即PHP代码没有为$val输出任何东西。试着在浏览器中查看源代码,下面是你将看到的:
myPlugin.start(); // I tried this, and it didn't work
And
<?php myPlugin.start($val); ?> // This didn't work either
这并不管用,因为PHP将尝试将myPlugin视为常量,当失败时,它将尝试将其视为字符串'myPlugin',它将尝试与PHP函数start()的输出连接,由于这是未定义的,它将产生一个致命的错误。
And
myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails
虽然这是最有可能工作的,因为PHP代码生成了带有预期参数的有效JavaScript,但如果失败,很可能是因为myPlugin还没有准备好。检查你的执行顺序。
您还应该注意到,PHP代码输出是不安全的,应该使用json_encode()进行过滤。
EDIT
因为我没有注意到myPlugin.start(<?=$val?>: \
正如@Second Rikudo指出的那样,要正确工作,$val需要包含右括号,例如:$val="42);"
这意味着PHP现在将生成myPlugin.start(42);并在JavaScript代码执行时按预期工作。
将数据转换为JSON
调用AJAX来接收JSON文件
将JSON转换为Javascript对象
例子:
步骤1
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, image FROM phone";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$v[] = $row;
}
echo json_encode($v);
$conn->close();
?>
步骤2
function showUser(fnc) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// STEP 3
var p = JSON.parse(this.responseText);
}
}
}
我想出了一个简单的方法来分配JavaScript变量使用PHP。
它使用HTML5数据属性来存储PHP变量,然后在页面加载时分配给JavaScript。
例子:
<?php
$variable_1 = "QNimate";
$variable_2 = "QScutter";
?>
<span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
<?php
下面是JavaScript代码
var variable_1 = undefined;
var variable_2 = undefined;
window.onload = function(){
variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
}