views:

70

answers:

3

hi,

thanks for looking,

when i use document.write, the whole pages goes blank and only displays the ad.

function __adthis(id) {
    $.getJSON('banner.php', function (data) {
        var adNum = Math.floor(Math.random() * data.ban.length);
        document.write("<SCRIPT TYPE='text/javascript'> SRC='+data.ban[0].link+'><\/SCRIPT>");
    });
}

this is a test, this is a test, this is a test, this is a test,

<div id="res"><script>`__adthis();`</script></div>
+3  A: 

Don't use document.write. Instead, use the DOM methods to create a <script> element and add it to the div:

var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('src', data.ban[0].link);
document.getElementById('res').appendChild(e);
casablanca
thanks for this it will help me in the furture but im still getting the same issues as before :(
jay
Same issue meaning page goes blank again?
casablanca
yes it still goes blank.
jay
Have a look at the script source, i.e. whatever `data.ban[0].link` contains. I'm guessing that script again includes `document.write`.
casablanca
jay
If you open that link in your browser, you will see that it is another JS file which uses `document.write`. Unfortunately, this no longer works with the current standards. See if you can get updated ad code from the provider.
casablanca
im so silly yes you are 100% right how did i forget that.
jay
A: 

HTML

<div id="ad_goes_here" />

JavaScript

function __adthis(id){
    $.getJSON('banner.php', function(data) {
        var adNum = Math.floor(Math.random()*data.ban.length);
        $("#ad_goes_here").html("<SCRIPT TYPE='text/javascript' SRC='+data.ban[0].link+'><\/SCRIPT>");
    });
}
GerManson
A: 

Just a side note about why document.write() does not work as expected. The W3C spec defines it this way:

Write a string of text to a document stream opened by open()

The Mozilla developer docs add this remark:

Writing to a document that has already loaded without calling document.open() will automatically perform a document.open call. Once you have finished writing, it is recommended to call document.close(), to tell the browser to finish loading the page. The text you write is parsed into the document's structure model.

In other words, using document.write() once the doc has been rendered triggers a document.open() call which:

Open a document stream for writing. If a document exists in the target, this method clears it.

Álvaro G. Vicario