yeshansachithak
yeshansachithak

Reputation: 840

Get data from JSON URL and Display results in (JQuery.ajax)

I need to know, I have a json file. Now I need to get that json data and display each data on my html page. I have few couple of codes. Help me here to fix that little thing.

  1. I need to alert before displaying result when is succeeded
  2. I want to alert before displaying error message when is error
  3. I just updated my question as that answer gives, Still its not working
  4. I need to display results inside the results div

This is my Test Jquery page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getJSON demo</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>

</head>
<body>

<h1>My Home Page</h1>

<div id="results">
    <!-- Display Jason Data -->
</div>

  <script>
    var newsURL_test = "http://localhost:81/testjs/data.json";

    jQuery.ajax({
        url: this.newsURL_test,
        type: "GET",
        success: function (data) {
            iterateJson(data);
        },
        error: function() {
            //
            alert("I'm in Error");
            alert(newsURL_test);
        }
    });

    function iterateJson(data) {
        $.each(data, function() {
                $.each(this, function(k,v) {
                    var capacity=v["_capacity"];
                    var description=v["_description"];
                    var dev_default_view=v["_dev_default_view"];
                    var deviceID=v["_deviceID"];
                    var deviceName=v["_deviceName"];
                    var deviceTypeID=v["_deviceTypeID"];
                    var projectID=v["_projectID"];
                    var roomID=v["_roomID"];
                    var roomName=v["_roomName"];
                    var room_admin_mail=v["_room_admin_mail"];                  
              });
         });

    }

</script>

</body>
</html>

This is my Json file code - data.json

{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]} 

Upvotes: 1

Views: 5716

Answers (1)

Vishwajeet
Vishwajeet

Reputation: 1683

Use the iterateJson function to iterate your json response.

jQuery.ajax({
    url: this.newsURL, //This URL is for Json file
    type:"GET",
    dataType: "json",
    success: function(data) {
        iterateJson(data);
    },
    error: function() {
        //Do alert is error
    }
});




function iterateJson(data)
{

    $.each(data, function() {
            $.each(this, function(k, v) {
                var capacity=v["_capacity"];
                 ......................................

          });
     });

}

Upvotes: 1

Related Questions