jQuery > Ajax methods

.getJSON() - Load JSON data from server in jQuery

How to load JSON data from server in jQuery?


To load JSON data from server, getJSON() method can be used. In this way, request is sent to the server using HTTP Get method.

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and also easy for machines to parse and generate. Read more about JSON at http://www.json.org/

<input type="button" id="btnJson" value="Load Json data" />
    
    <script>

        $("#btnJson").click(function () {
            $.getJSON("jQueryAjaxData.aspx", { format: "json" }, jsonCallback);
        });

        function jsonCallback(datas) {
            alert(datas[0].FirstName);
        }
    </script>

In the above code snippet, getJSON method is called to get the JSON data from server (jQueryAjaxData.aspx page). If the request is successful, the callback method (jsonCallback) is called where we can retrieve the data.

Server side response code (jQueryAjaxData.aspx.cs) is written below

if (Request.QueryString["format"] != null)
{
     string data = " [
                     { \"FirstName\": \"Sheo\", \"LastName\": \"Narayan\", 
                     \"City\": \"Hyderabad\" }, " +
                     "{ \"FirstName\": \"Jack\", \"LastName\": \"Jeel\", 
                     \"City\": \"NY\" }
                     ]";
// in the real time applicaiton, the original data comes from server Response.Write(data); }

Here, we have formed two object with FirstName, LastName and City property in JSON format and returned to the calling jquery function.

In the call back function of .getJSON() method, we are retrieving the FirstName of the first object that will alerted to the user and it would be “Sheo”.

 Views: 9631 | Post Order: 109



Write for us






Hosting Recommendations