When using the XHR object in order to send an HTTP request to specific URL address we are limited. We cannot initiate this HTTP request to servers other than the one from which the web page (in which the code in JavaScript that uses the XHR object is running) arrived.

The JSONP technique allows us to overcome this limitation. The following video clip overviews this technique and explains it using a code sample.

The code sample this video clip overviews includes two files. The first is a simple HTML file that we get from a specific HTTP server.

<!DOCTYPE html>
<html>
<head>
    <title>simple demo for jsonp</title>
</head>
<body>
    <div id="result"></div>
    <script type="text/javascript">
        function updateData(student)
        {
            var str = "name="+student.name+" id="+student.id+" average="+student.average;
            var node = document.getElementById("result");
            node.innerHTML = str;
        }
    </script>
    <script type="text/javascript" src="http://www.abelski.com/courses/ajax/data.json">
    </script>
    <script type="text/javascript">
        /*var xhr = new XMLHttpRequest();
        xhr.open("GET","http://www.abelski.com/courses/ajax/data.json",true);
        xhr.onreadystatechange = function()
        {
            if((xhr.readyState==4) && (xhr.status = 200))
            {
                var ob = JSON.parse(xhr.responseText);
                var str = "name="+ob.name+" id="+ob.id+" average="+ob.average;
                var node = document.getElementById("result");
                node.innerHTML = str;
            }
        };
        xhr.send();
        */
    </script>
</body>
</html>

The HTML file includes code in JavaScript that sends an HTTP request for getting a JSON document from another HTTP server. The second file is the JSON document.

updateData({
    "name":"dave",
    "id":123123,
    "average":94
});

 

You can find more video clips and training material for learning JavaScript and Ajax in my online free courses at abelski.lifemichael.com.

Leave a Reply

Your email address will not be published. Required fields are marked *