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?
Use
$([some element]).load([your URL])
this will load the data you have received and put it inside of the intended element.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):where
response
is your ajax content.Scope your modifications to a specific selector in your document, if using jquery and and assuming you have a
div
with idmycontent
and content of file is plain text:document.write
will replace all contents.You're using jQuery so try
.append()
if you want to keep existing code, like this: