jQuery.Ajax: $.get and document.write replace existing markup

孤街浪徒 提交于 2019-12-11 06:59:10

问题


I recently found out a method to include the content of an external file into the website using jQuery Ajax.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
  $.get("http://something.com/content.txt", function(a) {
    document.write("<p>Some text! - " + a + "</p>")
  });
</script>

The output will be following then:

<p>Some text! - Content from external file</p>

It works fine except that this code is overwriting the entire markup. Everything else will be excluded.

Any ideas how to fix this?


回答1:


document.write will replace all contents.

You're using jQuery so try .append() if you want to keep existing code, like this:

$.get("http://something.com/content.txt", function(a) {
  $("#element-where-inserting").append(a);
});



回答2:


Scope your modifications to a specific selector in your document, if using jquery and and assuming you have a div with id mycontent and content of file is plain text:

$("#mycontent").text(a);



回答3:


It's because the document.write() method rewrites the whole html document.

What you should do instead is find the element where you want to put the content of your response via javascript (use the html() method since you're using jQuery):

$("#elementId").html(response);

where response is your ajax content.




回答4:


Use $([some element]).load([your URL]) this will load the data you have received and put it inside of the intended element.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>

  $('some-div').load("http://something.com/content.txt")

</script>


来源:https://stackoverflow.com/questions/41580741/jquery-ajax-get-and-document-write-replace-existing-markup

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!