简体   繁体   English

从PHP运行JavaScript?

[英]running javascript from php?

I don't know if this is possible as i know php is server side and javascript is client side. 我不知道这是否可行,因为我知道php是服务器端,而javascript是客户端。

But i am trying to run this javascript code from an if isset inside a php page. 但是我正在尝试从PHP页面中的if isset运行此javascript代码。

I am using this code: 我正在使用此代码:

 <?php
    if( isset($_POST['submit2'])){
        echo "
            <script type=\"text/javascript\">
                $(document).ready(function(){
    setTimeout(function () {
        doWork();
        window.location.reload();
    }, 2000);

    function doWork() {
        $('#submit').trigger('click');
    }

});
</script>";
     }
  ?>

this javascript should click on the button named (submit) and it works fine if its not inside the PHP echo.. and I also checked to see if the if if( isset($_POST['submit2'])) actually returns a value and it does and it works as it should. 此javascript应该单击名为(submit)的按钮,如果它不在PHP echo中,则可以正常工作..我还检查了if( isset($_POST['submit2']))实际上返回了一个值而且确实如此,并且可以正常工作。

So, I don't know what the issue is here> 所以,我不知道这里是什么问题>

can some one please help me out with this? 有人可以帮我这个忙吗?

I have always found it best to keep my main javascript/jquery code within the head tag and use php to check and set variables that allow my scripts to run; 我总是发现最好将我的主要javascript / jquery代码保留在head标签中,并使用php检查并设置允许我的脚本运行的变量; echoing a javascript boolean into my JS block using php. 使用php将JavaScript布尔值回显到我的JS块中。 This way you know that the javascript is doing what it should natively and not worry about elements not being treated properly in the DOM. 这样一来,您就知道javascript在做本地应做的事情,而不必担心DOM中的元素没有得到正确处理。

So I would do this (I don't know the order in which you want things to happen so this might seem out of order but the principle should still be the same): 因此,我会这样做(我不知道您希望事情发生的顺序,所以这看起来可能不合时宜,但原理仍应相同):

<?php
if( isset($_POST['submit2'])){
    $varSet = "var set2 = 1;";
} else {
    $varSet = "var set2 = 0;";
}
?>


<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type=\"text/javascript\">
    $(document).ready(function(){

        <?php echo $varSet; ?>

        if(set2 == 1){
            setTimeout(function () {
                doWork();
                window.location.reload();
            }, 2000);

            function doWork() {
                $('#submit').trigger('click');
            }
        }
    });
</script>
</head>

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

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