StackOverflower
StackOverflower

Reputation: 5761

Render any response from ajax call (HTML and/or JS)

I wonder what's the most effective way to render ANYTHING that might come from an ajax call. The response can be html and/or javascript

I was doing it with document.write() since the ajax call was sync. Now I have to use async calls so I can't just write to the page using document.write, I have to add the content to a specific html object when the call finished.

I tried this

   $jQuery.ajax({
   url: "myURL.ashx",
   data: params,
   success: function(data){
        var newdiv = document.createElement('div');
        newdiv.innerHTML = data;
        document.getElementById('target').appendChild(newdiv);
   }   

but it doesn't work for any javascript returned, it get easily broken (this means; it doesn't render the content or it does weird things as showing the content in a new tab). I just work for simple scenarios.

I wonder if there is any better approach that works better than this.

Thanks!

EDIT

This code, for example, doesn't work as expected. It renders the content on a blank page instead of adding the content to the current page. I'm testing with FF 3.6. For simplicity, I'm harcoding the javscript on str var, but that script is returned from the server. The content returned by the server are ADS, the content is dynamic and totally random.

        var str = "<sc" + "ript language=\"JavaScript\" type=\"text/javascript\">";
        str += "document.write('<scr'+ 'ipt language=\"JavaScript\" src=\"anything.js\" type=\"text/javascript\"><\/scr' + 'ipt>');";
        str += "<\/script>";
        var newdiv = document.createElement('div');
        newdiv.innerHTML = str;
        document.getElementById('target').appendChild(newdiv);    

Upvotes: 1

Views: 4745

Answers (2)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

Well the jQuery equivalent of what you have there would be:

success: function(data){
    $('<div />')
        .append(data)
        .appendTo('#target');
}

You will have to explain what you mean by

doesn't work for any javascript returned

for a better answer.

If there are any <script> tags within data jQuery will evaluate them in the global scope if you use the jQuery.append function as I demonstrated above.

Update

Just remove the document.write statement. Only use document.write when the page is still loading.

<script src="anything.js" type="text/javascript"></script>

Upvotes: 1

mcgrailm
mcgrailm

Reputation: 17640

there are better ways to include js files than making an ajax call that loads javascript. I would look at .getScript()

Upvotes: 0

Related Questions