简体   繁体   English

如何从php调用JavaScript函数,将我重定向到另一个php文件

[英]how to call a javascript function from php which redirects me to another php file

I'm trying to call jsfunction() from php. 我正在尝试从php调用jsfunction()。 This jsfunction() will redirect me to code.php. 这个jsfunction()会将我重定向到code.php。 But, it's not working and not showing any error. 但是,它不起作用并且没有显示任何错误。

<?php
    $sid=$_GET['link'];
    echo '<script type="text/javascript">';
    echo  'jsfunction();';
    echo   '</script>';

?>

<script type="text/javascript"></script>
<script>
    function jsfunction()
    {
        var site_id="<?php echo $sid; ?>";
        window.location.href = "code.php?site_id=" + site_id; 
    }
</script>

As @Deljoei suggested you can redirect user using header. 正如@Deljoei所建议的,您可以使用标头重定向用户。 Coming to your question why this isn't working is because jsfunction(); 来到您的问题为什么不起作用的原因是jsfunction(); which you are calling before which result in error, because jsFunction is not defined. 因为未定义jsFunction,所以您在调用它之前会导致错误。 If you will change your code to 如果您将代码更改为

<?php
$sid=$_GET['link'];
?>

<script type="text/javascript"></script>
<script>
    function jsfunction()
    {
        var site_id="<?php echo $sid; ?>";
        window.location.href = "code.php?site_id=" + site_id; 
    }
</script>
<?php
    echo '<script type="text/javascript">';
    echo  'jsfunction();';
    echo   '</script>';
?>

then you will achieve what you want do. 那么您将实现您想要的。 Now you when jsFunction is called, it will not give error because it is defined earlier. 现在,当您调用jsFunction时,它不会给出错误,因为它是先前定义的。

You need to use php header for redirecting instead. 您需要使用php标头进行重定向。 Use the following code to redirect the user to the specific url : 使用以下代码将用户重定向到特定的url:

header('location:code.php?site_id='.$sid);
exit();

You need to declare function before use, try this: 您需要在使用前声明函数,请尝试以下操作:

<?php
    $sid=12;

?>

<script type="text/javascript"></script>
<script>
    function jsfunction()
    {
        var site_id="<?php echo $sid; ?>";
        window.location.href = "code.php?site_id=" + site_id; 
    }
</script>

<script type="text/javascript">;
jsfunction();
</script>;

Do like this: 这样做:

$sid=$_GET['link'];
if($sid){
header('location:code.php?site_id='.$sid);
exit();
}

I hope this helps! 我希望这有帮助!

Try this 尝试这个

<?php
    $sid=$_GET['link'];
    echo '<script type="text/javascript">';
    echo  'jsfunction('.$sid.');';
    echo   '</script>';

?>

<script type="text/javascript"></script>
<script>
    function jsfunction(id)
    {
        var site_id=id;
        window.location = "code.php?site_id=" + site_id; 
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM