问题
I am making a cross domain request using script tag hack and jsonp. In the callback function, I want to write the data received to DOM using document.write().
I know that I should use appendChild/innerHTML instead of doc.write(). My constraint is I do not have a class/id hook to the element I want to write to. I can only rely on document.write() to write "in place".
Following code is included in HTML div in a script tag.:
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
*/
Basically document.write does not work even with a static string inside the callback function. I thought that if docment.write is called before onload, it inserts text in the page as noted here JavaScript and HTML Script Tags
What is preventing the document.write() to write to DOM? Also, is there a better approach to do this.
回答1:
You should note that document.write();
calls an implicit document.open();
, thus, in effect, clearing everything you have had in the document so far.
It is impossible to add content to a document using document.write();
. It is, however, possible to use document.write();
to write an entire document.
You have several possible solutions:
- You can pass the target element as a GET parameter, as @kirilloid noted.
- You can insert an IFrame object at the desired place, and use
myIFrame.document.write();
to update its content.
This is basically happening because you are updating the content of a container that is the parent to your script code, and as such, is not closed yet.
Either that, or I'm entirely off track here which, let's face it, is entirely possible. ;-)
来源:https://stackoverflow.com/questions/8656509/document-write-in-jsonp-callback