JavaScript Document.Write Replaces All Body Content When Using AJAX
Solution 1:
You can't use document.write
once the document has completed loading. If you do, the browser will open a new document that replaces the current.
Use the innerHTML
property to put HTML code inside an element:
function gen_output(ad_content){
document.getElementById('mb_ad').innerHTML = ad_content;
}
Put the element before the script, so that you are sure that it exists when the callback function is called:
i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>
It doesn't matter much where you place the script, as nothing will be written to the document where it is.
Solution 2:
in case you cant control the remote script you might be able to write something like so:
<script>
var tmp = document.write;
document.write = function () {
document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;
Well it is a nasty hack but it seems to work...
Solution 3:
var div = document.createElement('div');
div.id = 'mb_ad';
div.innerHTML = ad_content;
Now, you can append this node wherever you want it to be.