【问题标题】:Issue Passing JS variable to PHP include file将 JS 变量传递给 PHP 包含文件的问题
【发布时间】:2013-03-24 19:22:30
【问题描述】:

我有一个 php 文件,我使用它来根据输入变量设置动态生成的页面。它从 index.html 页面开始,其中收集了一些变量,其中一些不是简单的字符串,而是复杂的 Google 地球对象。在提交该页面时,它会发布到另一个页面,您将被重定向到创建的文件。当我尝试在用于生成页面的 php 包含文件中使用该变量时,问题就来了.这是我目前正在尝试的。

点击此按钮后,变量 flyto1view 被设置。

 $("#flyto1").click(function(){          
    if (!flyto1view){
        flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
            $("#flyto1view1").val(flyto1view)
    }
    else {
        ge.getView().setAbstractView(flyto1view);

    }
});

然后从这里我尝试将值设置为 hidden 字段,但我不确定这种变量是否具有可以这样设置的值。发布后将此变量放到此处的最佳方法是什么

<? 
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address']))     {//if submit button clicked and name field is not empty 
$flyto1view1 = $_POST['flyto1']; 
$address = $_POST['address']; //the entered name 
$l = $address{0}; // the first letter of the name 

// Create the subdirectory: 
// this creates the subdirectory, $l, if it does not already exists 
// Note: this subdirectory is created in current directory that this php file is in. 
if(!file_exists($l))  
{  
mkdir($l);  
} 
// End create directory 

// Create the file: 
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name 
$fh = fopen($fileName, 'w') or die("can't open file"); 
// The html code: 
// this will outpout: My name is (address) ! 
$str = "    
<?  php include ('template.php') ?>

"; 
fwrite($fh, $str); 
fclose($fh); 
// End create file 

echo "Congradualations!<br /> 
The file has been created. 
Go to it by clicking <a href=\"$address.html\">here</a>."; 
die(); 
 } 

// The form: 
?> 

【问题讨论】:

    标签: php javascript html include


    【解决方案1】:

    首先。从用户输入创建文件是非常危险的。也许这只是您的代码的摘要,但是从输入的第一个字母执行mkdir 而不检查第一个字母实际上是一个字母而不是点、斜杠或其他字符不是一个好习惯。

    不管怎样,关于你的问题。我可能会使用 $_GET 变量传递给第二个文件。因此,在第二个文件中您使用 &lt;?php $_GET['foo'] ?&gt; 并在第一个文件中使用:

    echo "Congradualations!<br /> 
        The file has been created. 
        Go to it by clicking <a href=\"$address.html?foo=$flyto1view1\">here</a>."; 
    

    您也可以像这样将变量回显到您的模板中:

    $str = '
        <?php 
            $var = \'' . $flyto1view1 . '\';
            include (\'template.php\')
        ?>';
    

    【讨论】:

    • 同意风险,但我将是唯一使用此页面创建“模板化”文档的人。如果我要按照所示进行操作,我可以只使用 url 中的变量吗?
    • 是的,您可以在 url 中使用该变量。我将编辑我的评论以反映这一点。
    • 我还更新了我的评论,展示了如何直接将 var 添加到模板中。
    • 好的,最后一个问题。这种方法是使用隐藏字段吗?有什么方法可以在不使用隐藏字段的情况下抓取或发布变量?
    • 我不确定您说的是哪个隐藏字段。你能发布你的 HTML 吗?
    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多