我有一个变量在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>
将数据转换为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");
}