Search code examples
jqueryjsongetjson

How to check for ID in URL and output only that with getJSON


This is my HTML.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>

   $(function() {

   var people = [];

   $.getJSON('test.json', function(data) {
       $.each(data.person, function(i, f) {
          var tblRow = "<tr>" + "<td>" + f.ID + "</td>" +"<td>" + f.Destination + "</td>" +
           "<td>" + f.SupplierName + "</td>"  + "</tr>"
           $(tblRow).appendTo("#userdata tbody");
     });

   });

});
</script>
</head>

<body>
<table id= "userdata" border="2">
  <thead>
  <th>ID</th>
    <th>Destination</th>
    <th>SupplierName</th>
    </thead>
  <tbody>
  </tbody>
</table>
</body>
</html>

This is my test.json file

{
  "person" : [
    {
      "ID" : 100,
      "Destination" : "brisbane",
      "SupplierName" : "Hilton Brisbane",

    },
    {
      "ID" : 101,
      "Destination" : "brisbane",
      "SupplierName" : "Hotel Grand Chancellor Brisbane",

    },
    {
      "ID" : 102,
      "Destination" : "brisbane",
      "SupplierName" : "Park Regis North Quay",

    } 
  ]
}

What I'm trying to do

The output works fine. But here's what Im trying to do.

My website will look like www.website.com?deal=100

I want to look for the ID at the end of 'deal' parameter and only output that ID's information from the JSON array. JSON array has an object with the same ID. Can you please help?


Solution

  • do a if to test if the id corresponds with the id from the url

     $.getJSON('test.json', function(data) {
           $.each(data.person, function(i, f) {
              if(window.location.href.split('=')[1] == f.ID) {//asumes that you have only the deal as a url param
              var tblRow = "<tr>" + "<td>" + f.ID + "</td>" +"<td>" + f.Destination + "</td>" +
               "<td>" + f.SupplierName + "</td>"  + "</tr>"
               $(tblRow).appendTo("#userdata tbody");
    }
         });