简体   繁体   中英

Content is not loaded into div using javascript

How come the content form the "body.html" file isn't loaded into the "section2"-div?

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<script src="jquery-1.6.2.min.js"></script>
<script language='javascript' type='text/javascript'>
$(document).ready(function(){
  alert("Document ready");  

        $.get("body.html", function(data){
            alert("Data Loaded: ");
            $("#section2").html(data);
        });
});

</script>

</head>
<body>

<div id="section2">

</div>

</body>
</html>

body.html:

Content for all!

Both alerts are triggered.

Thank you in advance!

i'd use load() instead

 $("#section2").load("body.html")

EDIT - i'v seen that $.get works also with two parametrs so i just leave the load() advice

The problem is that the response headers content type has to be "text/html" when calling body.html.

To avoid errors, use:

$.ajax({
    url:"body.html",
    dataType: "text/html",
    success: function(data){
        $("#section2").html(data);
    }
});

or

$.get("body.html",function(data){
        $("#section2").html(data);
    }
, "text/html");

or

$("#section2").load("body.html");

Check out the jQuery.get documentation. It looks like jQuery is trying to help you out by sending the data back as a JS XML document, when you really want HTML. Try $.get(<url>, null, <successFunc>, "html") (see the documentation on the $.ajax method for more on those parameters)

This worked for me...

All I did was link to the external jquery and changed what file I was calling...

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> 
<script language='javascript' type='text/javascript'>
$(document).ready(function(){
  alert("Document ready");  

        $.get("serverTime.php", function(data){
            alert("Data Loaded: ");
            $("#section2").html(data);
        });
});

</script>

</head>
<body>

<div id="section2">

</div>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM