简体   繁体   中英

Load Javascript into ajax loaded content

I am new to working with AJAX and have some experience with Java/Jquery. I have been looking around for an solution to my problem but i cant seem to find any.

I am trying to build a function in a webshop where the product will appear in a popup window instead of loading a new page.

I got it working by using this code:

$(".product-slot a").live('click', function() {
  var myUrl = $(this).attr("href") + " #product-content";
  $("#product-overlay-inner").load(myUrl, function() {
  });
  $("#product-overlay").fadeIn();
  return false;
});

product-slot a = Link to the product in the category page.
product-content = the div i want to insert in the popup from the product page.
product-overlay-inner = The popup window.
product-overlay = The popup wrapper.

The problem that i now have is that my Javascript/Jquery isnt working in the productpopup. For example the lightbox for the product image or the button to add product to shoppingcart doesnt work. Is there anyway to make the javascript work inside the loaded content or to load javascript into the popup?

I hope you can understand what my problem is!

Thank you in advance!

EDIT: The platform im using has jquery-ui-1.7.2

I know this is an old thread but I've been working on a similar process with the same script loading problem and thought I'd share my version as another option.

I have a basic route handler for when a user clicks an anchor/button etc that I use to swap out the main content area of the site, in this example it's the ".page" class.

I then use a function to make an ajax call to get the html content as a partial, at the moment they are php files and they do some preliminary rendering server side to build the html but this isn't necessary.

The callback handles placing the new html and as I know what script I need I just append it to the bottom in a script tag created on the fly. If I have an error at the server I pass this back as content which may be just a key word that I can use to trigger a custom js method to print something more meaningful to the page.

here's a basic implementation based on the register route handler:

var register = function(){
    $(".page").html("");
    // use the getText ajax function to get the page content:
    getText('partials/register.php', function(content) {
        $(".page").html(content);
        var script = document.createElement('script');
        script.src = "js/register.js";
        $(".page").append(script);
    });
};




/******************************************
 * Ajax helpers
 ******************************************/
// Issue a Http GET request for the contents of the specified Url.
// when the response arrives successfully, verify it's plain text
// and if so, pass it to the specified callback function
function getText(url, callback) {
    var request = new XMLHttpRequest();
    request.open("GET", url);
    request.onreadystatechange = function() {
        // if the request is complete and was successful -
        if (request.readyState === 4 && request.status === 200) {
            // check the content type:
            var type = request.getResponseHeader("Content-Type");
            if (type.match(/^text/)) {
                callback(request.responseText);
            }
        }
    };
    // send it:
    request.send(null); // nothing to send on GET requests.
}

I find this a good way to 'module-ize' my code into partial views and separated JavaScript files that can be swapped in/out of the page easily. I will be working on a way to make this more dynamic and even cache these 'modules' for repeated use in an SPA scenario.

I'm relatively new to web dev so if you can see any problems with this or a safer/better way to do it I'm all ears :)

Yes you can load Javascript from a dynamic page, but not with load() as load strips any Javascript and inserts the raw HTML.

Solution: pull down raw page with a get and reattach any Javascript blocks.

Apologies that this is in Typescript, but you should get the idea (if anything, strongly-typed TypeScript is easier to read than plain Javascript):

    _loadIntoPanel(panel: JQuery, url: string, callback?: { (): void; })
    {
        // Regular expression to match <script>...</script> block
        var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
        var scripts: string = "";
        var match;

        // Do an async AJAX get
        $.ajax({
            url: url,
            type: "get",
            success: function (data: string, status: string, xhr)
            {
                while (match = re.exec(data))
                {
                    if (match[1] != "")
                    {
                        // TODO: Any extra work here to eliminate existing scripts from being inserted
                       scripts += match[0];
                    }
                }

                // Replace the contents of the panel
                //panel.html(data);

                // If you only want part of the loaded view (assuming it is not a partial view)
                // using something like
                panel.html($(data).find('#product-content'));

                // Add the scripts - will evaluate immediately - beware of any onload code
                panel.append(scripts);

                if (callback) { callback(); }
            },
            error: function (xhr, status, error)
            {
                alert(error);
            }
        });
    }

Plain JQuery/Javascript version with hooks:

It will go something like:

    var _loadFormIntoPanel = function (panel, url, callback) {
        var that = this;
        var re = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
        var scripts = "";
        var match;
        $.ajax({
            url: url,
            type: "get",
            success: function (data, status, xhr) {
                while(match = re.exec(data)) {
                    if(match[1] != "") {
                        // TODO: Any extra work here to eliminate existing scripts from being inserted
                        scripts += match[0];
                    }
                }
                panel.html(data);
                panel.append(scripts);
                if(callback) {
                    callback();
                }
            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    };

$(".product-slot a").live('click', function() {
    var myUrl = $(this).attr("href") + " #product-content";
    _loadFormIntoPanel($("#product-overlay-inner"), myUrl, function() {
         // Now do extra stuff to loaded panel here
    });
  $("#product-overlay").fadeIn();
  return false;
});

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