JQuery .get doesnt execute Javascript

前端 未结 2 796
终归单人心
终归单人心 2021-01-22 13:45

I am using JQuery .get method to retrieve some content from a webpage (page 1) and show it in a div in the main page. The problem is the content retrieved contains some javascri

相关标签:
2条回答
  • 2021-01-22 14:10

    Inline JavaScript won't execute unless you run eval() on it. You can read more about that here:

    • Executing inside retrieved by AJAX
    • Can scripts be inserted with innerHTML?

    An eval() solution could look something like this, but I would consider it bad practice:

    $.get(url, function(response) {          
        var newContent = $(response).find("#right");      //Find the content section of the response
        var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
        var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.
    
        oldContent.replaceWith(newContent);
    
    
        //Find all inline script tags in the new content and loop through them
        newContent.find("script").each(function() {
            var scriptContent = $(this).html(); //Grab the content of this tag
            eval(scriptContent); //Execute the content
        });
    });
    

    A better solution is to set a identifier/name on the #right tag and execute the code needed for that specific content.

    Something like:

    <div id="right" data-page-name="index">
        <!-- Content -->
    </div>
    
    <div id="right" data-page-name="about-us">
        <!-- Content -->
    </div>
    

    A simple solution that just passes the page name to a function that will execute the code depending on page would look something like this:

    $.get(url, function(response) {          
        var newContent = $(response).find("#right");      //Find the content section of the response
        var contentWrapper = $("#wrap");         //Find the content-wrapper where we are supposed to change the content.
        var oldContent = contentWrapper.find("#right");   //Find the old content which we should replace.
    
        oldContent.replaceWith(newContent);
    
        var pageName = newContent.attr("data-page-name");
    
        pageSpecificActions(pageName);
    });
    
    function pageSpecificActions(pageName) {
        if (pageName == "index") {
            //Run the code for index page
        } else if (pageName == "about-us") {
            //Run the code for about us page.
        }   
    };
    

    This keeps the JavaScript code from being inline and doesn't use eval(). Even better would be to use events for when page content change, but this will be enough for now.

    0 讨论(0)
  • 2021-01-22 14:24

    You can use .load() function instead of .get(). It automatically executes the scripts that are contained in the response.

    Here is the documentation: .load()

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