简体   繁体   中英

Get data from json web service using only JavaScript and jQuery

I have downloaded a sample application using this url http://www.zachhunter.com/2010/04/json-objects-to-html-table/ . The part which is working perfectly is :

<script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script>
<script src="scripts/json.htmTable.js" type="text/javascript"></script>
<script src="scripts/json.debug.js" type="text/javascript"></script>
<link href="styles/default.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
    $(document).ready(function () {
        /* ASSOC ARRAY - Detail View */
        var json1 = { "d": [{ "__type": "acation", "id": "001", "date": "2010-06-01
                      00:00:00", "iod": "1", "mer": "ABC ", "tity": "6", "ot": 
                      "12,500", "nt": "75000", "ou": "A", "rep": "we", "perc": "34", 
                      "ine": "one", "year": "2009", "ct": "ABC ", "alet": "90000",  
                      "pro": "1500", "stats": "ive", "crnt": "5000", "ter": "AA"}] }

        /* NORMAL ARRAY - Detail View */
        var json2 = { "d": [{ __type: "acation", id: "001", date: "2010-06-01 
                      00:00:00", iod: "1", mer: "ABC ", tity: "6", ot: "12,500", nt: 
                      "75000", ou: "A", rep: "we", perc: "34", ine: "one", year: 
                      "2009", ct: "ABC ", alet: "90000", pro: "1500", stats: "ive", 
                      crnt: "5000", ter: "AA"}] }

        /* NORMAL ARRAY - Table View */
        var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName
                      \":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary 
                      Zupers\"}]" }

        $('#DynamicGridLoading').hide();

        delete json1.d[0]["__type"];
        delete json2.d[0]["__type"];

        $('#DynamicGrid').append(CreateDetailView(json1.d, "lightPro", true)).fadeIn();
        $('#DynamicGrid').append(CreateDetailView(json2.d, "lightPro", true)).fadeIn();
        $('#DynamicGrid').append(CreateTableView(json3.d, "lightPro", true)).fadeIn();

    });
</script>

</head>
 <body>
   <form id="form1" >
   <div id="DynamicGrid" >
     <div id="DynamicGridLoading" >
        <img src="images/loading.gif" /><span> Loading Data... </span>
     </div>
   </div>
  <br />
  <a href="jsonservice_api.html">Json web service</a>
  </form>
 </body>

Its working fine, but when I try to use a free json webservice like this weather api: http://api.worldweatheronline.com/free/v1/weather.ashx?q=dehradun&format=json&num_of_days=5&key=3tkb34yntmwqn23uambzdvgm in the following way I am getting nothing.

  <script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: "http://api.worldweatheronline.com/free/v1/weather.ashx?q=dehradun&
                  format=json&num_of_days=5&key=3tkb34yntmwqn23uambzdvgm",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{}",
            success: function (res) {
                $('#DynamicGrid').append(CreateTableView1(res, "CoolTableTheme", 
                                    true)).fadeIn();
            }
        });
    });

</script>

The definition for CreateTableView is in one of the js file included in scripts tag having definition as follows :

function CreateTableView(objArray, theme, enableHeader) {
  // set optional theme parameter
  if (theme === undefined) {
      theme = 'mediumTable'; //default theme
  }

  if (enableHeader === undefined) {
      enableHeader = true; //default enable headers
  }

  var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

  var str = '<table class="' + theme + '">';

  // table head
  if (enableHeader) {
      str += '<thead><tr>';
      for (var index in array[0]) {
          str += '<th scope="col">' + index + '</th>';
      }
      str += '</tr></thead>';
  }

  // table body
  str += '<tbody>';
  for (var i = 0; i < array.length; i++) {
      str += (i % 2 == 0) ? '<tr class="alt">' : '<tr>';
      for (var index in array[i]) {
          str += '<td>' + array[i][index] + '</td>';
      }
      str += '</tr>';
  }
  str += '</tbody>'
  str += '</table>';
  return str;
}

What about trying metwit weather API ?
Here is a working and simple jQuery example : http://jsbin.com/isukam/1

Check weather resource for more information.

Disclosure: I own this API.

This is likely a cross domain/same origin policy issue. Web browsers block content from other domains (so if you're on localhost or www.yoursite.com and you're calling a webservice on http://api.worldweatheronline.com it will be blocked).

To confirm this is the case you can open your web browser's developer tools and there will likely be an error message in the console or network area about a cross domain call. (To open the developer tools use Ctrl-Shift-I in Chrome, Ctrl-Shift-K in Firefox and F12 in IE).

If the service supports them you can use either JSONP or CORS . Otherwise you could create a service on your own project that acts as a proxy, calling the service on another domain and then returning the results. (The cross domain restriction is a browser security feature only, so you can call the service from your ASP.NET, PHP, Java etc services on the server side without issue).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM