我有一个变量在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>

当前回答

这是在2022年对我有用的,我使用这个解决方案来获取当前用户的电子邮件

我使用PHP创建了一个短代码,并将其添加到PHP .function:

function my_get_current_user_email(){
    $current_user = wp_get_current_user();
    $email = $current_user->user_email;
    return $email;  
} 
add_shortcode( 'get_email', 'my_get_current_user_email');

然后使用div来包装短代码:

 <div id="target-content" style="display: none;">
[get_email]
 </div>

最后,使用JavaScript访问Div的内容:

const databox = document.getElementById("target-content");
const dataContent = databox.textContent;
console.log(dataContent)

这工作完美地为我想要的,我希望它也会为你工作。

其他回答

经过大量的研究,我发现最简单的方法是简单地传递各种变量。

在服务器脚本中,你有两个变量,你试图将它们发送到客户端脚本:

$php_var1 ="Hello world";
$php_var2 ="Helloow";
echo '<script>';
echo 'var js_variable1= ' . json_encode($php_var1) . ';';
echo 'var js_variable2= ' . json_encode($php_var2) . ';';
echo '</script>';

在页面上调用的任何JavaScript代码中,只需调用这些变量。

<?php

    $val = $myService->getValue(); // Makes an API and database call

    echo "
        <script>
            myPlugin.start({$val});
        </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");
}

我非常喜欢WordPress使用其enqueue和本地化函数的工作方式,因此遵循这个模型,我编写了一个简单的类,根据脚本依赖关系将脚本放入页面,并为脚本提供额外的数据。

class mHeader {

    private $scripts = array();

    /**
     * @param string $id        Unique script identifier
     * @param string $src      Script src attribute
     * @param array  $deps       An array of dependencies ( script identifiers ).
     * @param array  $data       An array, data that will be json_encoded and available to the script.
     */
    function enqueue_script($id, $src, $deps = array(), $data = array()) {
        $this->scripts[$id] = array('src' => $src, 'deps' => $deps, 'data' => $data);
    }

    private function dependencies($script) {
        if ($script['deps']) {
            return array_map(array($this, 'dependencies'), array_intersect_key($this->scripts, array_flip($script['deps'])));
        }
    }

    private function _unset($key, &$deps, &$out) {
        $out[$key] = $this->scripts[$key];
        unset($deps[$key]);
    }

    private function flattern(&$deps, &$out = array()) {

        foreach($deps as $key => $value) {
            empty($value) ? $this->_unset($key, $deps, $out) : $this->flattern( $deps[$key], $out);
        }
    }

    function print_scripts() {

        if (!$this->scripts)
            return;

        $deps = array_map(array($this, 'dependencies'), $this->scripts);
        while ($deps)
            $this->flattern($deps, $js);

        foreach($js as $key => $script) {
            $script['data'] && printf("<script> var %s = %s; </script>" . PHP_EOL, key($script['data']), json_encode(current( $script['data'])));
            echo "<script id=\"$key-js\" src=\"$script[src]\" type=\"text/javascript\"></script>" . PHP_EOL;
        }
    }
}

对enqueue_script()函数的调用用于添加脚本、设置脚本的源和对其他脚本的依赖关系,以及脚本所需的其他数据。

$header = new mHeader();

$header->enqueue_script('jquery-ui', '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js', array('jquery'));
$header->enqueue_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
$header->enqueue_script('custom-script', '//custom-script.min.js', array('jquery-ui'), array('mydata' => array('value' => 20)));

$header->print_scripts();

并且,上面示例的print_scripts()方法将发送以下输出:

<script id="jquery-js" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script id="jquery-ui-js" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js" type="text/javascript"></script>
<script> var mydata = {"value":20}; </script>
<script id="custom-script-js" src="//custom-script.min.js" type="text/javascript"></script>

不管脚本'jquery'是在'jquery-ui'之后排队,它是在'jquery-ui'中定义的,它依赖于'jquery',所以它是在'jquery-ui'之前打印的。 额外的数据为'自定义脚本'是在一个新的脚本块,并放在它前面,它包含mydata对象,持有额外的数据,现在可用于'自定义脚本'。

将数据转换为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);
      }
   }
}