0

I am making an async call from a webpage to another resource at a url like /example/url/here.html which contains a partial view and inserting the response into the innerHTML of a div on the first page. However, the partial view here.html might contain <script> references and some inline script that doesn't get loaded/run when inserting to innerHTML.

I'm wondering if jQuery's load() function would solve this, and if so how to implement a similar function in javascript, as I cannot use jQuery.

Here's the code I'm using that isn't working:

     function (elemId, url) {

        var successCallback = function (responseText) {
            var elem = document.getElementById(elemId);
            elem.innerHTML(responseText);
        };

        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                successCallback(xmlhttp.responseText);
            }
        };

        xmlhttp.open("GET", url, true);
        xmlhttp.send();

    }
7
  • You need to do what jQuery does: parse the responseText and look for <script> elements. It extracts them and creates new <script> nodes with the content. Commented Jan 17, 2015 at 1:49
  • So if I create new <script> nodes it will load/execute them? Commented Jan 17, 2015 at 2:04
  • Take the jQuery source code for the function, after all, jQuery is just Javascript. Commented Jan 17, 2015 at 2:04
  • @Nit The code for this is buried deep inside the .html() code, it's not in .load() itself. Commented Jan 17, 2015 at 2:05
  • @Zack Yes. You can also use eval() to execute the code. Commented Jan 17, 2015 at 2:06

1 Answer 1

0

I think what you want to do is load the html partial via jquery like this:

<div id="partial" ></div>

$('#partial').load('somefile.html');
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that's what I'm trying to figure out is how to implement that without jQuery.
Ah, I see what you mean. github.com/jquery/jquery/blob/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.