LearnFast.Ninja

JavaScript Ajax example function script with JSON

Create items.txt file with JSON format and fill it with some items. Create AJAX_Example.html file. Copy the following code. Note that there is code for broswer from IE7+ and another code for IE6 and IE5, we use the if statement with window.XMLHttpRequest to indicate. We also do workaround for IE for the seconed time we click the button.

Step 1: Create items.txt file with JSON format and fill it with some items. 

{

    "itemsList":

    [

        {

            "item": "5.0MP Wide Angle 4-LED Night Viewing Digital Car",

            "price": "$98.70"

        },

        {

            "item": "5.0MP CMOS Digital Video Camcorder",

            "price": "$50.40"

        },

        {

            "item": "Mini 2.0M Pixels CMOS DV Video Camera",

            "price": "$31.10"

        }

    ]

}

 
Step 2: Create AJAX_Example.html file. Copy the following code. 

<html>

<head>

    <title>AJAX Example</title>

    <script type="text/javascript">

        function getItems() {

            // -- Step 1 ----------------------------------------------------------

            // code for broswer from IE7+

            if (window.XMLHttpRequest) {

                xmlHttp = new XMLHttpRequest();

            }

                // else there is another code for IE6 and IE5

            else {

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

            }

            // -- Step 2 ----------------------------------------------------------

            xmlHttp.onreadystatechange = function () {

                // if action success

                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

                    var ItemsDiv = document.getElementById("items");

                    // set the file content into the div element

                    ItemsDiv.innerHTML = xmlHttp.responseText;

                }

            }

            // -- Step 3 ----------------------------------------------------------

            // workaround for IE for the seconed time we click the button

            var date = new Date();

            // open and send

            xmlHttp.open("GET", "items.txt?Date=" + date.getTime(), true);

            xmlHttp.send();

        }

    </script>

</head>

<body>

    <div id="items"></div>

    <input type="button" value="get items" onclick="getItems()" />

</body>

</html> 
 
Result: 


Tags

javascript

ajax xmlhttprequest activexobject