Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jsonp回调中的document.write_Javascript_Dom_Dom Events_Cross Domain - Fatal编程技术网

Javascript jsonp回调中的document.write

Javascript jsonp回调中的document.write,javascript,dom,dom-events,cross-domain,Javascript,Dom,Dom Events,Cross Domain,我正在使用脚本标记hack和jsonp进行跨域请求。在回调函数中,我想使用document.write()将接收到的数据写入DOM 我知道我应该使用appendChild/innerHTML而不是doc.write()。我的限制是我没有一个类/id钩子指向我想要写入的元素。我只能依靠document.write()来写“就地” 以下代码包含在脚本标记的HTML div中: function request_jsonp(){ var script = document.createElement(

我正在使用脚本标记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
,它会在页面中插入所述文本


是什么阻止
document.write()
写入DOM?还有,有没有更好的方法来实现这一点?

您应该注意
document.write()
调用隐式
文档.open(),因此,实际上,清除了文档中迄今为止的所有内容。
使用
document.write()向文档添加内容是不可能的。但是,可以使用
document.write()
编写整个文档

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

  • 您可以将目标元素作为GET参数传递,如@kirilloid所述

  • 您可以在所需位置插入IFrame对象,并使用
    myIFrame.document.write()
    以更新其内容
这基本上是因为您正在更新作为脚本代码父级的容器的内容,因此尚未关闭


要么如此,要么我完全偏离了轨道,让我们面对现实,这是完全可能的

“我没有一个类/id钩子指向我想写入的元素。”--然后通过jsonp的GET param发送。我想我没有说清楚。要通过GET发送,元素上首先需要有一个id/类。您可以在所有其他元素中使用索引,例如:
Array.prototype.indexOf.call(document.getElementsByTagName('*'),element)
“您可以在所需的位置插入一个IFrame对象”我该怎么做?我没有需要插入iframe的父div的id/class挂钩。基本上我想说的是.parentNode.appendChild(myIFrame)你是对的。在不知道目标元素的情况下,这是行不通的。您可以始终包含
document.write()的代码在包含的脚本文件中。这样,直到容器关闭后才会执行写块。还应该注意,回调函数位于JSONP模式的客户端,因此应该知道通过JSONP创建的页面的细节。如果没有,你应该修改你的设计。