2012-12-16 77 views
0

例如,这是我的PHP代码:如何将此PHP代码与HTML和Javascript结合使用?

<?php 

if($country_code == 'US') 
{ 
     header('Location: http://www.test.com'); 
} 

else 
{ 
     header('Location: http://www.test.com/'); 
} 

?> 

我试图使用Javascript代码进行跟踪,它是</body>标签上面。

我曾尝试PHP代码HTML结合不同的方式,我都试过分开放置HTML的PHP也低于,一个例子:

<html> 
<head></head> 
<body> 
    <?php 

    ?> 
<script></script> 
</body> 
</html> 

我最远的是,它跟踪的点击,但它没有重定向给我这个错误:

`Warning: Cannot modify header information - headers already sent by` 

将不胜感激任何建议和帮助,谢谢!

+1

如果您已经开始输出文档,那么您不能使用php的'header',您必须使用不同的方法重定向(即JavaScript的'window.location.href')。 –

+0

在某种意义上,PHP从上到下按顺序工作。一旦DOM开始呈现内容,PHP不仅可以停止,反转,放置您的标题,然后重建,如果有意义=]将该PHP放在页面的顶部,然后从那里开始工作。 –

+0

'$ country_code'从哪里来? – Martijn

回答

0

你必须尝试一些类似下面的轨道:在您的索引页检查了美国参数的值

<?php 

if($country_code == 'US') 
{ 
     header('Location: http://www.test.com/?us=yes'); 
} 

else 
{ 
     header('Location: http://www.test.com/?us=no'); 
} 

?> 

然后。另外,应注意没有任何输出应该在头函数之前打印作废警告:

Warning: Cannot modify header information - headers already sent by

1

把PHP重定向代码在文档的开头输出任何东西之前。请检查?>标记之后和<?php标记之前的空格,因为这些标记将被打印出来,并且将为此发送响应标题,因此您将无法修改标题以重定向。

0

问题是PHP在JavaScript之前运行。所以你需要在JavaScript中获取PHP变量。

<?php 
// your normal code here, like connection to DB 
?> 

<script>var test = <?php> echo $thatVariable; <?> </script> 
0

您不能在php的header()标记之前向客户端发送输出。 因此,您可以生成一个重定向页面,通过js获取国家信息并将其发送到php(使用例如表单提交)。之后,您可以通过php头重定向到accoording页面()

0
<?php 
if($country_code === 'US'){ 

    echo "<script> window.location.href='http://www.test.com1'</script>"; 

} 
else{ 

    echo "<script> window.location.href='http://www.test.com2/'</script>"; 

} 

?>