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>
    <title>simple demo for jsonp</title>
    <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 type="text/javascript" src="http://www.abelski.com/courses/ajax/data.json">
    <script type="text/javascript">
        /*var xhr = new XMLHttpRequest();
        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;

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.



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 *