Load code in HTML using jQuery?

I know this is possible, and I looked through numerous examples. And I'm afraid I already know the answer to my question, but maybe I missed something. I thought this did not work because I am running this code locally and not on the server.

In my tag:

<script type="text/javascript" src="jquery-1.5.js"></script>

<script type="text/javascript">
    $(document).ready(function() {
        $("#test").load("test.html");
        } );
</script>

In my body tag:

<div id="test"></div>

My external code (inside 'test.html ")

<div>This is what you should be seeing!</div>

Doesn't that work? In addition, in my external html document, I need to configure it with all the additional tags so that the document looks like this:

<html>
    <head>
        <title>
        </title>
    </head>
    <body>

<div>This is what you should be seeing!</div>
</body>
</html>

All my files are in the same directory.

Thank.

+3
source share
3 answers

Well, your code should work on a web server! Please let me know if you are doing this from your desktop.

<script src="jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
    $("#test").load("./test.html"); //  also try /test.html
    } );
</script>
<div id="test"></div>
+1
source

Plain

$.get('test.html', function(data) {
    $('#test').html(data);
});

.load()

UPDATE:

insted replace,

$('body').append(data)
+1

Use an optional selector after the url to put in the target <body> (or something else):

   // will load the contents of test.html body-element into #test  
   $("#test").load("test.html body");
0
source

Source: https://habr.com/ru/post/1790266/


All Articles