访问从其他PHP文件中的JavaScript变量

问题描述 投票:0回答:3

我有threePHP文件。拳头是index.php和第二是cal.php和第三是search.php。在cal.php我在JavaScript设置两个变量。

<script>
    $(document).ready(function () {
        var startDate = "hi";
        var endDate = "there";
        console.log("Callback is being set!");
    });
</script>

然后我包括此cal.phpsearch.php文件在我index.php文件。

<div class="col-md-6 mt-20 pad-sm-0">
                <?php
                include("searchUI.php");
                ?>
            </div>
            <div class="col-md-6 mt-20 pad-sm-0 hidden-sm hidden-xs">
                <?php
                include("calendarUI.php");
                ?> 
            </div>

index.php一个按钮,点击我要访问cal.phpsearch.php文件中设置的变量。我尝试以下,但我在控制台中看到不确定的。

function performSearch() {
        console.log(window.startDate);
        console.log(window.endDate);
}
javascript
3个回答
0
投票

var具有的功能范围,所以任何定义有只能在函数内部访问。

你可以声明不var关键字,尽管它是在实践中高度皱起眉头它添加变量到全球范围。 (除非你用use strict;运行会抛出一个错误)

$(document).ready(function () {
    startDate = "hi";  // creates global variable, not recommended
    endDate = "there";
    console.log("Callback is being set!");
});

一个稍微像样的做法*将刚才设置的变量键在窗口对象类似于您试图访问它们的方式。

<script>
$(document).ready(function () {
    window.startDate = "hi";
    window.endDate = "there";
    console.log("Callback is being set!");
});
</script>

0
投票

改变你的脚本如下:

<script>
    var startDate, endDate;;
    $(document).ready(function () {
        startDate = "hi";
        endDate = "there";
        console.log("Callback is being set!");
    });
</script>

希望工程


0
投票

您可以删除var关键字,这将使全球变量像下面。虽然有全局变量不是推荐的方法,因为有多个同名的全局变量可以有不良副作用。

全局变量被默认绑定到全局的window对象,所以你并不需要明确写入window.startDate。

<script>
  $(document).ready(function () {
     startDate = "hi";
     endDate = "there";
     console.log("Callback is being set!");
  });
</script>
© www.soinside.com 2019 - 2024. All rights reserved.