简体   繁体   中英

load the content of html file into the div

I am a beginner. The problem I am dealing with is probably very simple to solve ;) I am working on a web page where the text content is loaded from external html files into the div. This is done when a user clicks on a menu item.

This is my code html :

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/menu.css">
<script type="text/javascript" src="js/js.js"></script>

</head>
<body>
          <div>
                      <ul>      
                          <li><a id="teachers" href="#" name="teachers" onclick="getdata()">
                            Teachers
                          </li> 
                        </ul>
          </div>

          <div id="page"  name="" >
            bla bla bla ...
          </div>

</body>
</html>

And this is my code ajax:

var _xhr;

function getdata(){

    _xhr= new XMLHttpRequest();
    _xhr.onreadystatechange=callback;
    _xhr.open("POST", "teachers.html", true);
    _xhr.send();

    function callback(){
        var _target = document.getElementById("page");
        _target.innerHTML=_xhr.responseText;
    }

}

I would like to load the html file (teachers.html) into the div (id="page") when I click on the link (Teachers)

Please could someone help me.

Thanks in advance.

尝试将POST更改为GET,看看是否可行。

for this case i recommend to user jQuery Load function. its easy to use and fit your needs. you can find more in the following link: http://api.jquery.com/load/

Its pretty hard to know if you don't tell us what happened. I´ve figure out (maybe) a problem

Try Change your code to

function getdata(){

    function callback(){
        var _target = document.getElementById("page");
        _target.innerHTML=_xhr.responseText;
    }


    _xhr= new XMLHttpRequest();
    _xhr.onreadystatechange=callback;
    _xhr.open("POST", "teachers.html", true);
    _xhr.send();
}

Have you tried bringing the var _xhr; inside the function?

i tried the below.. it worked

function getdata(){
                var xmlhttp;
                xmlhttp=new XMLHttpRequest();
                xmlhttp.open("get","techers.html",false);
                xmlhttp.send();
                document.getElementById("page").innerHTML=xmlhttp.responseText;

            }

How about using an ajax call?

$.get( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

Documentation: http://api.jquery.com/jquery.get/

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