How to embed php script in javascript?

前端 未结 6 863
余生分开走
余生分开走 2020-12-11 12:26

I want to know if I can include php scripts in javascript[1] the same way it can be done in html[2]

server.php:


        
6条回答
  •  一向
    一向 (楼主)
    2020-12-11 12:40

    You can use output buffering to achieve something similar, although it's not possible to directly embed PHP code in JS.

    Example:

    server.php

    
    

    client.php - (.php extension enables the ability to parse PHP tags, but really outputs JS)

    
    function foo() {
        var i = '';
        console.log( i );
    }
    

    Edit: If the server.php file will only return a simple string, then you can modify your code for client.php. Notice how I said "return" instead of output - If your server.php outputs anything, it will be sent to the browser as output (not what you want). Alternatively, you can set a variable in server.php which gets outputted in client.php, or encapsulate your code in a function:

    server.php

    
    

    client.php

    
    function foo() {
        var i = '';
        console.log( i );
    }
    

    Note: You may also want to add a call to html_entities or htmlspecialchars.

提交回复
热议问题