简体   繁体   English

跨域 Ajax 调用不使用 document.write

[英]Cross Domain Ajax Call Not Working with document.write

I am using this Ajax script below to make cross domain Ajax calls which works fine if i use alert(txt);我正在使用下面的这个 Ajax 脚本来进行跨域 Ajax 调用,如果我使用alert(txt); , but when i change it to document.write(txt); ,但是当我将它更改为document.write(txt); to print the result it stops working and i am not sure why it is not working,打印结果它停止工作,我不确定为什么它不工作,

It might be something stupid but i just can't figure it out这可能是一些愚蠢的事情,但我就是想不通

    function xss_ajax(url) {
        var script_id = null;
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script.setAttribute('src', url);
        script.setAttribute('id', 'script_id');

        script_id = document.getElementById('script_id');
        if(script_id){
            document.getElementsByTagName('head')[0].removeChild(script_id);
        }

        // Insert <script> into DOM
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    function callback(data) {
        var txt = '';
        for(var key in data) {
           txt += key + "  " + data[key];

        }
      //alert(txt);
      document.write(txt);
   }

    var url = "http://myserver.com";

I believe that in some browsers you cannot call document.write after the document is done loading...我相信在某些浏览器中,您无法在文档加载完成后调用 document.write ...

Edit: This stuff I'm striking out certainly does not work.编辑:我删除的这些东西肯定不起作用。 As Teemu points out, calling "open" clears out the document.正如 Teemu 指出的那样,调用“打开”会清除文档。 Also, MDN says that calling.write will implicitly call.open if you did not call it yourself.此外,MDN 表示如果您没有自己调用 calling.write 将隐式调用它。 The other possibility is that the document is just not rendering because when you start writing you'll have to close the stream. You could try (not really sure if this works): 另一种可能性是文档没有呈现,因为当您开始编写时,您必须关闭 stream。您可以尝试(不确定这是否有效):

 document.open(); document.write('stuff'); document.close();

However, I would strongly recommend that you just use a more standard method for writing to the document such as appendChild or using a framework (eg jQuery):但是,我强烈建议您只使用更标准的方法来写入文档,例如 appendChild 或使用框架(例如 jQuery):

function callback(data) {
    var txt = '';
    for(var key in data) {
       txt += key + "  " + data[key];

    }
    //alert(txt);
    //document.write(txt);
    document.body.appendChild(document.createTextNode(txt));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM