【问题标题】:Getting error when trying to write javascript inside PHP [closed]尝试在 PHP 中编写 javascript 时出错 [关闭]
【发布时间】:2014-12-23 00:04:12
【问题描述】:

我正在尝试使用此 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

我哪里做错了?

【问题讨论】:

  • 语法高亮显示明显错误
  • 为什么你甚至需要在 php 中使用echo 编写 javascript?如果您甚至无法看到已经突出显示的简单语法错误,建议您不要尝试混合两种语言
  • 这不是制作模板的理想方式。考虑以 HTML 模式(即在 PHP 标记之外)编写所有 HTML 和 JavaScript,并且仅在需要时才进入 PHP。见an example here

标签: javascript php


【解决方案1】:

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

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 包含在 &lt;script type="text/javascript" src="file.js"&gt;&lt;/script&gt; 中。

【讨论】:

  • 很好的支持@developerwjk 我猜有些人喜欢欺负新人而不是试图帮助/指导他们
猜你喜欢
  • 1970-01-01
  • 2018-03-31
  • 2017-03-01
  • 1970-01-01
  • 2021-03-31
  • 2017-05-15
  • 2013-05-20
  • 1970-01-01
  • 2016-04-20
相关资源
最近更新 更多