Snoopy Snoopy - 7 months ago 25
Javascript Question

alert(reponseText + $(.class))

I want print Hello World. but it doesn't work. Why? The problem is in line 30, how can I change this line for print "Hello World." by class "example"? I already tryed var

x = y.getElementsByClassName("example");
and
var x = variavelhtttp.responseXML.getElementsByClassName("example");
but without success.

index.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Load page</title>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<script type="text/javascript">
if(window.XMLHttpRequest){
variavelhtttp = new XMLHttpRequest();
}else{
alert("Withouth Ajax!");
}
</script>

</head>

<body>

<button type="button" onclick="loadDoc()">Go</button>

<script type="text/javascript">
function loadDoc(){
variavelhtttp= new XMLHttpRequest();
variavelhtttp.open("GET","text.html",false);
variavelhtttp.send();
var y = variavelhtttp.responseText;
window.alert(y);
var x = $( ".example" ).html(y);
alert(x);
}
</script>

</body>
</html>


text.html

<html>
<head>
<title></title>
</head>
<body>
<div class="example">Hello World.</div>
</body>
</html>

Answer

You can use jQuery to do It:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Load page</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">

        $(function() {

            $('#btn').click(function() {

                $('#loadContentHere').load('text.html');

                // alert('Hello World!');
            });
        });
    </script>
</head>

<body>
    <p>
        <input id="btn" type="button" value="Click Me">
    </p>
    <p>
        <div id="loadContentHere"></div>
    </p>
</body>
</html>

jQuery's load function documentation: http://api.jquery.com/load/

Comments