尝试在 PHP 中编写 JavaScript 时出错


Getting error when trying to write javascript inside PHP

我正在尝试使用此javascript函数进行重定向,该函数可以向用户显示重定向消息并重定向到给定的URL,但是每当我尝试运行php时都会出现错误

<?php
include 'theme.php';
/*ceklogin();*/
css();
if($_POST['wget-send'])
    {
        $dir=$_POST['dir'];
        $link=$_POST['link'];
        /*exec('cd '.$dir,$out);*/
        exec('echo '.$link.' > /tmp/wget-download-link.txt',$out);
        exec('wget -P '.$dir.' -b -i /tmp/wget-download-link.txt -o /www/wget.log -c -t 100 -w 10',$out);
        echo $out[2];
        echo "
                <script type="text/javascript">   
                function Redirect() 
                    {  
                        window.location="http://www.google.com"; 
                    } 
                document.write("You will be redirected to a new page in 5 seconds"); 
                setTimeout('Redirect()', 5000);   
                </script>
             ";
        exit();
    }
echo "<br><br><form action=wget_log.php method='"post'">";
echo "Download directory :<br><input type='"text'" name='"dir'" size='"15'" value='"/mnt/usb/'"/><br>";
echo '<br>Download link :<br>';
echo "<textarea name='"link'" rows='"4'" cols='"35'"></textarea><br><br>";
echo '<input type="submit" name="wget-send" value="Send" />';
echo "</form></div>";
foot();
echo '
</div>
</body>
</div>
</html>';
?>

错误说:

Parse error: syntax error, unexpected 'text' (T_STRING), expecting ',' or ';' in /www/wget.php on line 14

我哪里做错了?

当你在双引号中使用双引号时,你必须转它们。这意味着您将'放在内部的前面。

echo "<script type='"text/javascript'">";
将单引号

放在单引号中时,您也会这样做:

echo '<script type=''text/javascript''>';

但是当混合它们时,没有必要。 即:

echo "<script type='text/javascript'>"; //single inside double
echo '<script type="text/javascript">'; //double inside single

但实际上对于像Javascript这样的长文本,你应该关闭PHP标签,然后重新打开它。 即:

<?php
//some php
if(whatever)
{
?>
 <script type="text/javascript"> blah blah blah </script>
<?php
}
?>

或者更好的是,尽可能将Javascript包含在<script type="text/javascript" src="file.js"></script>中。