The JSONP Technique

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.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

What are Anti Patterns?

Anti Patterns

Unlike design patterns, anti patterns just seem to be a solution. However, they are not a solution and they cause additional costs.

Virtual Threads in Java Professional Seminar

Virtual Threads in Java

The use of virtual threads can assist us with improving the performance of our code. Learn how to use virtual threads effectively.

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences