简体   繁体   中英

How to Load HTML(with javascript in it) content using ajax and pure javascript

I have been working on a project that uses the 'one page app' concept: All the pages are loaded using jQuery and ajax, something like this :

$.ajax({
    url : some_url
    ,data: some_data
    ,success : function(resp){
        $("#somediv").html( resp.view ) 
    }  
});

And like this, it has been working fine . All the HTML, CSS and JS included on "resp.view" behave like a charm.

But, one day I needed to do it without jQuery :

var xhr = new XMLHttpRequest();
xhr.open("POST",  someurl);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);

        somediv.innerHTML = data.view;

    }
};

xhr.send(some_data);

The pure JS way works fine to load only HTML and CSS include on "data.view" ... but, it does not execute any javascript included in the HTML returned ...

I could use document.head.append to add all the scripts I need, but, there is some JS code into the html ... and, I deal with lots of different pages as reponse ... so, it is not an option to add the dependencies manually.

So:

How can I insert an string, that contains a HTML page with styles and scripts, to my current page and get it to behave such a html page ? how the jQuery does that ?

.... Scope

I am working now in a script that injects some html codes into my client's website. And, at the moment I call my script and invoke an ajax to request the page, I can not be sure if jQuery is loaded on DOM. That's why, in this case, I need pure JS. Then, the HTML returned has the jQuery source and others.

The workaround I found to deal with this matter was to load my local jQuery source into DOM beforehand, and then, use jQuery ajax to do the job as always. it works, but, I got curious how so !

For JS loaded via AJAX, you could do:

somediv.innerHTML = data.view;
somediv.querySelectorAll('script').forEach(function(script) {
    var el = document.createElement('script');

    if (script.src) {
        el.setAttribute('src', script.src)
    } else {
        el.innerHTML = script.innerHTML;
    }

    script.replaceWith(el);
});

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