简体   繁体   中英

Ajax and external JS scripts

Have the issue here when I dynamically load a php page the external JS file linked into that PHP pages doesn't seem to take effect. There is know JS code in the HTML file to call functions, the JS files does all the work by modifying certain tags.

HTML page will load the PHP file which is linked to the JS script. Relevant code below.

This does work if loaded directly, just not when loaded dynamically I've similar issues like this in the past where the solution was to use the call back feature when loading the content however since all the JS is in a external file not sure of the best method.

HTML code to load PHP file

<script>
   $(document).ready (function() {
      $('#test').click(function(event) {
        $('#content').empty();
        $('#content').load('view/search.php');
      })
    })
</script>

How the JS is linked into the PHP file

       <script type="text/javascript" src="edit.js"></script>

Again all the code works when loading the PHP page directly.

Many Thanks

Loading HTML containing script tags is supported. However, keep in mind that load will just insert your content into the DOM. Therefore, if you have a <script src="edit.js"></script> being inserted, the DOM will try to load edit.js from the current directory, not from the directory of the php file you're loading.

make the php file output the content of edit.js in a script tag

eg

<script>
   <?php
      echo file_get_contents('edit.js');
   ?>
</script>

If i understand your question correctly this has worked for me. Then the js file is loaded when the click is made. The cons of this method is that if it is clicked multiple times, the file will load each time, cluttering your DOM which can result in a slow site.

<script>
   $(document).ready (function() {
      $('#test').click(function(event) {
        $('#content').empty();
        $('#content').load('view/search.php', function() {
               $.getScript(path+to+script);
        });
      })
    })
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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