0

My js code is not working with document loaded via ajax.

Below is ajax code :

var xhr;

xhr = new XMLHttpRequest();

function xhrDocOpen(doc,placeID){
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4 && xhr.status==200){
            document.getElementById(placeID).innerHTML=xhr.responseText;
            }
    }
    xhr.open('GET',doc,true);
    xhr.send();
}

As you see, it's pure js code. do not using jquery. I saw some of solutions in here, they were all using jquery..(example: success {js code})

But I want to solve the problem with pure js code.

How can I do that?

goJson
  • 203
  • 2
  • 6
  • 12
  • The scripts that are inside of the `xhr.responseText` are not evaluated when you add the html code to you site using `.innerHTML` you need to search for those scripts yourself (e.g. after you added the html code to your page) and evaluate them in the global context: therefore you could look at the [jQuery.globalEval](https://github.com/jquery/jquery/blob/10399ddcf8a239acc27bdec9231b996b178224d3/src/core.js#L259) – t.niese Sep 15 '14 at 05:32
  • run after innerHTML: [].slice.call(document.getElementById(placeID).querySelectorAll("script")).map(function(a){(eval)(a.textContent);}); – dandavis Sep 15 '14 at 05:57

1 Answers1

0

The problem is that not all browsers work the same way when doing pure js (that is actually one of the things jquery does, to implement the same function differently depending on browser)

Creating the xhr for loading a document can be done in a couple of different ways depending on browser:

xhr = new XMLHttpRequest()

xhr = new window.ActiveXObject("Microsoft.XMLDOM")

xhr = document.implementation.createDocument("","",null);

So you will need to take these into account, to make it worse there is a difference if you want to load the file asynchronosly or synchronosly.

This answer assumes you want to load a file from disk and not from a webserver. But the answer is still that there are at least two ways of doing ajax requests depending on browser. If you don't want to handle all this (and make changes as new browser versions emerge) use jquery.

Rickard Staaf
  • 2,650
  • 2
  • 14
  • 14