JavaScript Document.Write 在使用 AJAX 时替换所有正文内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2360076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:55:41  来源:igfitidea点击:

JavaScript Document.Write Replaces All Body Content When Using AJAX

javascriptajax

提问by Russ Bradberry

I am creating a simple ajax call that retrieves the content of a specified url and writes it to the page. The problem I am having is that it replaces the entire body contents with this information

我正在创建一个简单的 ajax 调用,它检索指定 url 的内容并将其写入页面。我遇到的问题是它用此信息替换了整个正文内容

here is the JS:

这是JS:

(function(){
    var mb = window.mb = {};

    function get_ad(url, parameters){
        var result = "";
        var http_request = false;

        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/html');
            }
        } else if (window.ActiveXObject) { // IE
            var avers = ["Microsoft.XmlHttp", "MSXML2.XmlHttp", "MSXML2.XmlHttp.3.0", "MSXML2.XmlHttp.4.0", "MSXML2.XmlHttp.5.0"];
            for (var i = avers.length -1; i >= 0; i--) {
                try {
                    http_request = new ActiveXObject(avers[i]);
                    if (http_request){
                        break;  
                    }
                } catch(e) {}
            }
        }
        if (!http_request) {
            alert('Cannot create XMLHTTP instance');
            return false;
        }

        http_request.onreadystatechange = function(){
                                              if (http_request.readyState == 4) {
                                                 if (http_request.status == 200) {
                                                    gen_output(http_request.responseText);
                                                 } else {
                                                    alert('Error');
                                                 }
                                              }
                                           }

        http_request.open('GET', url + parameters, true);
        http_request.send(null);
    }

    function gen_output(ad_content){
        document.write("<div id=\"mb_ad\">");
        document.write(ad_content);
        document.write("</div>");
    }

    get_ad("http://localhost/test/test.html", "");
})();

and here is the html:

这是html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
    i am text before <br/>
    <script type="text/javascript" src="mb.js"></script>
    <br />
    i am text after 
</body>
</html>

using firebug to inspect, i do not see the text before or the text after, just the <div id="mb_ad">and the content from the test.html page. If i remove the ajax call and just do 3 document.writesthe text before and the text after will display properly. jQuery is not an option, I have to do this without the help of a large library as size and speed are of the essence.

使用萤火虫进行检查,我看不到之前或之后的文本,只有<div id="mb_ad">test.html 页面中的和 内容。如果我删除 ajax 调用并只执行 3document.writes之前的文本和之后的文本将正确显示。jQuery 不是一种选择,我必须在没有大型库帮助的情况下执行此操作,因为大小和速度至关重要。

回答by Guffa

You can't use document.writeonce the document has completed loading. If you do, the browser will open a new document that replaces the current.

document.write一旦文档完成加载,您将无法使用。如果这样做,浏览器将打开一个替换当前文档的新文档。

Use the innerHTMLproperty to put HTML code inside an element:

使用该innerHTML属性将 HTML 代码放入元素中:

function gen_output(ad_content){
  document.getElementById('mb_ad').innerHTML = ad_content;
}

Put the element before the script, so that you are sure that it exists when the callback function is called:

将元素放在脚本之前,以便在调用回调函数时确定它存在:

i am text before
<div id="mb_ad"></div>
i am text after
<script type="text/javascript" src="mb.js"></script>

It doesn't matter much where you place the script, as nothing will be written to the document where it is.

放置脚本的位置并不重要,因为不会将任何内容写入文档所在的位置。

回答by Leon Fedotov

in case you cant control the remote script you might be able to write something like so:

如果您无法控制远程脚本,您可以编写如下内容:

<script>
var tmp = document.write;

document.write = function () {
  document.getElementById('someId').innerHTML = [].concat.apply([], arguments).join('');
};
</script>
<script .....>
document.write = tmp;

Well it is a nasty hack but it seems to work...

嗯,这是一个讨厌的黑客,但它似乎有效......

回答by N 1.1

var div = document.createElement('div');
div.id = 'mb_ad';
div.innerHTML = ad_content;

Now, you can append this node wherever you want it to be.

现在,您可以将此节点附加到任何您想要的位置。

回答by raven myers

you can use <script>document.body.innerHTML+="//Your HTML Code Here";</script>

您可以使用 <script>document.body.innerHTML+="//Your HTML Code Here";</script>

回答by Aivils ?toss

Same Leon Fedotov answer but more jQuery

相同的 Leon Fedotov 回答但更多 jQuery

{
  var old_write = document.write;

  var $zone = $('.zone.zone_' + name);
  // redefine document.write in this closure
  document.write = function () {
    $zone.append([].concat.apply([], arguments).join(''));
  };
  // OA_output[name] contains dangerous document.write
  $zone.html(OA_output[name]);

  document.write = old_write;
}

回答by kundun

I had the same problem with the following code :

我对以下代码有同样的问题:

$html[] = '<script>
           if($("#mf_dialogs").length == 0) {
               document.write("<div id=\"mf_dialogs\"></div>");
           }
           </script>';

The following code replaces document.write efficiently :

以下代码有效地替换了 document.write :

$html = '<div id="dialogHolder"></div>
         <script>
              if($("#mf_dialogs").length == 0) {
                  document.getElementById("dialogHolder").innerHTML="<div id=\"mf_dialogs\"></div>";
              }
         </script>';