08 February 2014

A Very Simple GET Application (AJAX)

My former student sent me a pm this am regarding a sample code in getting external files using AJAX in native JavaScript code.

Working with AJAX with or without using 'other' framework is fine. But let me show you the difference between getting a text file using a native JavaScript against jQuery framework.

Native:

function testGET()
    {  
        "use strict;"      
        var xhr = false;
        if (window.XMLHttpRequest) {
      
            xhr = new XMLHttpRequest();
      
        } else {
      
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
      
        xhr.open("GET", "SampleText.txt", true);
        xhr.send(null);
        xhr.onreadystatechange = function() {      
      
            if (xhr.readyState == 4) {

                if (xhr.status == 200 || window.location.href.indexOf("http") == -1) {
              
                    var obj = document.getElementById("myDiv");      
                    obj.innerHTML = xhr.responseText;          
                  
                }
            }              
        };      
    }



With jQuery:

$(document).ready(function(){
  $("button").click(function(){
    $("#myDiv").load("SampleText.txt");
  });
});



Which one is better? They're both fine with me.

Hope you could learn something from this. Suggestions and reactions are welcome (*_*)

No comments:

Post a Comment