jQuery.Ajax: $.get and [removed] replace existing

2019-07-23 03:03发布

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?

4条回答
倾城 Initia
2楼-- · 2019-07-23 03:31

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>

查看更多
等我变得足够好
3楼-- · 2019-07-23 03:36

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楼-- · 2019-07-23 03:45

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);
查看更多
手持菜刀,她持情操
5楼-- · 2019-07-23 03:56

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);
});
查看更多
登录 后发表回答