【发布时间】:2011-12-28 13:25:45
【问题描述】:
我正在使用脚本标签 hack 和 jsonp 发出跨域请求。在回调函数中,我想使用document.write()将接收到的数据写入DOM。
我知道我应该使用 appendChild/innerHTML 而不是 doc.write()。我的限制是我没有要写入的元素的类/id 挂钩。我只能靠document.write()写“就地”了。
以下代码包含在 HTML div 中的脚本标记中。:
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
*/
基本上document.write 即使在回调函数中使用静态字符串也不起作用。我认为如果在onload 之前调用document.write,它会在页面中插入文本,如here JavaScript and HTML Script Tags 所述
是什么阻止了document.write() 写入 DOM?另外,有没有更好的方法来做到这一点?
【问题讨论】:
-
“我没有要写入的元素的类/id 挂钩。” -- 然后通过jsonp的GET参数发送。
-
我想我没有说清楚。要通过 GET 发送它,首先需要在元素上显示一个 id/class。
-
您可以在所有其他元素中只使用一个索引,例如:
Array.prototype.indexOf.call(document.getElementsByTagName('*'), element)
标签: javascript dom dom-events cross-domain