Forum Moderators: open
function request_jsonp(){
var script = document.createElement('script');
var server_path = 'http://somedomain.com/?q=querystring&callback=request_callback';
script.setAttribute('src', server_path);
document.getElementsByTagName('head')[0].appendChild(script);
console.log('data requested');
// document.write('hello world'); // this gets written
}
function request_callback(data){
console.log('data received');
document.write(data);
}
request_jsonp();
window.onload = function(){
console.log('onload fired');
}
/*
above code prints
data requested
data received
onload fired
*/
<div>
<script type='text/javascript' src="myscript.js"></script>
<!-- Myscipt has the jsonp code and callback function listed above -->
</div>
var iframe = document.createElement("iframe");
/*I do not want to append to body though. I want to append to div */
document.body.appendChild(iframe);
var doc = iframe.document;
if(iframe.contentDocument){
doc = iframe.contentDocument; // For NS6
}
else if(iframe.contentWindow){
doc = iframe.contentWindow.document; // For IE5.5 and IE6
}
doc.open();
doc.write(data);
doc.close();
My constraint is I do not have a class/id hook to the element I want to write to.
var divs = document.getElementsByTagName('div');
var DATA_RECEIVER_DIV = divs[divs.length - 1]; //the current div this script is within at time of page load
function request_callback(data){
console.log('data received');
DATA_RECEIVER_DIV.innerHTML = data;
}
request_jsonp();
I have tried this approach. It fails when you add another div after the target div on the page. It should find the last div of the currently parsed ones, target div being the last. However, when I get the divs array, it has the subsequent div on the page as well.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
<title>Some Title</title>
<script type="text/javascript">
window.onload = function () {
DATA_RECEIVER_DIV.innerHTML = ' (this is div 2, aka: DATA_RECEIVER_DIV)';
};
</script>
</head>
<body>
<div>div 1</div>
<div>div 2
<script type="text/javascript">
var divs = document.getElementsByTagName('div');
var DATA_RECEIVER_DIV = divs[divs.length - 1];
</script>
</div>
<div>div 3</div>
<div>div 4</div>
</body>
</html>
Are you saying you have implemented EXACTLY as I showed? I don't believe so. The definition of DATA_RECEIVER_DIV must be standalone global code as I showed to be read as the page is loaded, as opposed to in a function call later on or anything like that