简体   繁体   中英

call javascript in html block after load by Ajax

So I have a PHP page that can be loaded two way. it can be directly embedded on a page using includes(), or another page that is made to load the first page on user demand using AJAX. My problem comes with these lines of code:

echo "<script>";
    echo "we_start_slide('" . $we_gallery['gallery_name'] . "', " . $we_gallery['display']->output() . ", " . $we_gallery['settings']['slide_time'] . ");";
    echo "we_slide_show_btns('" . $we_gallery['gallery_name'] . "');";
echo "</script>";

This works great on direct loads. However AJAX, as you know, doesn't run javascripts when it's loaded. Because the code requires dynamic variables only known to the PHP script I can't just call the functions in the AJAX function. I was wondering if there is anyway to tell JavaScript to run the contents of that script tag after it loads?

Put the js script inside the ajax done function

$.ajax({

}).done(function() {
  <?php
     echo "<script>";
     echo "we_start_slide('" . $we_gallery['gallery_name'] . "', " . $we_gallery['display']->output() . ", " . $we_gallery['settings']['slide_time'] . ");";
     echo "we_slide_show_btns('" . $we_gallery['gallery_name'] . "');";
     echo "</script>";
  ?>
});

For reference here is jquery ajax api http://api.jquery.com/jquery.ajax/

There is a few options. Note counselledCount: txt is a post variable, so on the page which processes your ajax request access it with $_POST["counselledCount"] Here is another example:

$.post("../includes/process-results.php", {counselledCount: txt, currentPageReset: "yes"}, function(result){
        showAjaxResult(result);
});

now instead of using ajax done, on the page which processes the ajax request and sends that request back send your script back with the request.

$request = "<script>";
$request .= "we_start_slide('" . $we_gallery['gallery_name'] . "', " . $we_gallery['display']->output() . ", " . $we_gallery['settings']['slide_time'] . ");";
$request .= "we_slide_show_btns('" . $we_gallery['gallery_name'] . "');";
$request .= "</script>";

So the answer was eval()

eval(document.getElementById('slide_start').innerHTML);

by adding a id to the script tag I could pull the script into the the call back function then use eval() to execute it Thank you A. lau for pointing me the right way.

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