How to define a variable in JavaScript with PHP echo function?

前端 未结 7 1362
囚心锁ツ
囚心锁ツ 2020-12-18 13:33

How do I define a variable in javascript with echo function, from the external php file?

We have theconfigfile.php, thejsfile.js an

相关标签:
7条回答
  • 2020-12-18 14:37

    Unless you're making a post to another server via JSONP then you might just consider using a relative path hard-coded in your Javascript that way you don't need to send the path from the server to the client:

    ...
        $.ajax({
            type: "POST",
            url: "home.php",
            data: dataString,
            cache: false
        });
    ....
    

    But, if this is a URL that changes frequently and it really does need to be configurable then you can echo out the PHP variable as script something like this"

    <html>
    ...
    <script src="thejsfile.js" type="text/javascript">
    <script type="text/javascript">
        // 'path' is a variable that is defined in thejsfile.js
        path = '<?php echo htmlentities($path)  ?>';
    </script>
    
    ...
    

    Whenever you output info from the server to the client (especially as Javascript) you have to be REALLY careful that it is escaped to prevent scripting attacks (ie allowing people to inject javascript into your code). In this case there is no reason to allow any type of html characters.

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