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

2019-07-23 03:47发布

问题:

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>