Is it okay to use PHP inside a jQuery script?

前端 未结 7 1370
误落风尘
误落风尘 2021-02-20 03:56

For example:

$(document).ready(function(){
    $(\'.selector\').click(function(){
        
    });
});


        
相关标签:
7条回答
  • 2021-02-20 04:18

    PHP is a "backend" language and javascript is a "frontend" language. In short, as long as the PHP code is loaded through a web server that understands PHP - the downside is that you have to inline the JS, losing caching ability (there are workarounds to parse php in .js files but you shouldn't really do this). To the user it will just look like javascript and HTML. Here's the server order:

    1. User requests page.
    2. Apache (or equivalent) notices this is a php file. It then renders all the php that are between php tags.
    3. Apache sends the page to the user.
    4. User's browser sees the JavaScript and executes it.

    Just be sure the PHP is outputting valid JavaScript.

    0 讨论(0)
  • 2021-02-20 04:21

    It won't slow down the page; the PHP runs on the server and emits text which is sent to the browser, as on any PHP page. Is it bad practice? I wouldn't say "bad" necessarily, but not great. It makes for messy code - in the event where I need to do something like this, I usually try to break it up, as in:

    <script>
        var stuff = <?php print $stuff; ?>;
        var blah = "<?php print $blah; ?>";
    
        // Do things in JS with stuff and blah here, no more PHP mixed in
    </script>
    
    0 讨论(0)
  • 2021-02-20 04:23

    If you are trying to bound some PHP code with the click event then this is impossible in the way you are trying and PHP code will be executed as soon as page load without waiting for a click event.

    If you are trying to generate final javascript or jquery code using PHP then this is okay.

    0 讨论(0)
  • 2021-02-20 04:28

    No it's not. Just as long as you know that the JS is executed after the PHP page is parsed.

    0 讨论(0)
  • 2021-02-20 04:33

    you have a better choice to use ajax that runs the php script when you are handling a click event

    $(document).ready(function(){
        $('.selector').click(function(){
           $.ajax({url:"phpfile.php",type:"POST",
    data:"datastring="+value+"&datastring2="othervalue,
    
    ,success:function(data){
    //get the result from the php file after it's executed on server
    }
    
    });
        });
    });
    
    0 讨论(0)
  • 2021-02-20 04:34

    PHP is executed on the server, and then the javascript will be executed on the client. So what you'd be doing here is using php to generate javascript that will become the function body. If that's what you were trying to do then there's nothing wrong with doing it.

    If you thought you were going to invoke some PHP code from javascript, then you're on the wrong track. You'd need to put the PHP code in a separate page and use an ajax request to get the result.

    0 讨论(0)
提交回复
热议问题