【问题标题】:document.write in jsonp callbackjsonp回调中的document.write
【发布时间】: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


【解决方案1】:

您应该注意到document.write(); 调用了一个隐含的document.open();,因此实际上清除了您目前在文档中拥有的所有内容。 使用document.write(); 向文档添加 内容是不可能的。但是,可以使用document.write(); 来编写整个文档。

您有几种可能的解决方案:

  • 您可以将目标元素作为 GET 参数传递,正如 @kirilloid 所指出的那样。
  • 您可以在所需位置插入 IFrame 对象,并使用myIFrame.document.write(); 更新其内容。

这基本上是因为您正在更新作为脚本代码父级容器的内容,因此尚未关闭。

要么这样,要么我在这里完全偏离轨道,让我们面对现实,这是完全可能的。 ;-)

【讨论】:

  • "您可以在所需位置插入 IFrame 对象" 我该怎么做?我没有需要在其中插入 iframe 的父 div 的 id/class 挂钩。基本上我想说this.parentNode.appendChild(myIFrame)
  • 你是对的。在不知道目标元素的情况下,这是行不通的。您始终可以在包含的脚本文件中包含 document.write(); 的代码。这样,在容器关闭之前,写入块不会被执行。
  • 还应注意,您的回调函数驻留在 JSONP 模式的客户端,因此应了解您通过 JSONP 创建的页面的细节。如果没有,你应该修改你的设计。
猜你喜欢
  • 1970-01-01
  • 2013-10-17
  • 2014-12-31
  • 1970-01-01
  • 2019-12-07
  • 2013-12-07
  • 2013-09-28
  • 2013-04-29
相关资源
最近更新 更多