Shaun
Shaun

Reputation: 398

Loading a HTML file using JS

I was following this tutorial on loading files with Javascript. I've followed the tutorial and no file loads. Here's the my code:

<script type="application/javascript"
        src="http://server2.example.com/Users/1234">
</script>

Now in this tutorial (Here) It says It should load the file into a div. Do you guys know what's happening?

Upvotes: 1

Views: 128

Answers (2)

sawan
sawan

Reputation: 2381

you may use jquery ajax or get function which will fetch data from given url and print that data into given div

<script type="application/javascript">
$.get( "http://server2.example.com/Users/1234?jsonp=parseResponse"
       ,function( data ) {
                        $( "body" ).append( "Name: " + data.name ) // John
                        .append( "Time: " + data.time ); //  2pm
                        }
       ,"json" );
</script>

Refer this link for more details Jquery.get()

Upvotes: 0

mavrosxristoforos
mavrosxristoforos

Reputation: 3643

Loading JSON

The "tutorial" you mentioned, is the Wiki page on JSON. The line of code you provided is copied exactly from that page, and if you read the contents correctly, it isn't talking about loading HTML files from javascript, but loading JSON data from Javascript.

In fact, the page clearly says that this approach cannot allow you to access the JSON data, because it isn't assigned to do anything, and even if it does load the data as an object, you have no pointer to that object!

Instead, the same page suggests using something like

<script type="application/javascript"
      src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</script>

so that you can use the function parseResponse with the data.

Loading HTML

Since you want to load some additional HTML, after you load the page, you should do something like:

Example Code: (partly copied from the page I gave you)

<script type="text/javascript">
  function loadXMLDoc(filename) {
    var xmlhttp;
    if (window.XMLHttpRequest)  {
      xmlhttp=new XMLHttpRequest();
    }
    else {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
      if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        after_load_function(xmlhttp.responseText);
      }
    }
    xmlhttp.open("GET",filename,true);
    xmlhttp.send();
    }

    function after_load_function(responseText) {
      document.getElementById("myDiv").innerHTML = responseText;
    }

    window.onload = function() {
      loadXMLDoc("your_html_filename.html");
    }
</script>

Upvotes: 1

Related Questions