简体   繁体   English

仅使用JavaScript和jQuery从JSON Web服务获取数据

[英]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/ . 我已经使用此网址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. 它的工作正常,但是当我尝试使用像这样的天气api的免费json网络服务时: http : //api.worldweatheronline.com/free/v1/weather.ashx? q=dehradun&format=json&num_of_days=5&key=3tkb34yntmwqn23uambzdvgm我什么也没得到。

  <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 : CreateTableView的定义在scripts标记中包含的js文件之一中,其定义如下:

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 ? 尝试使用metwit weather API怎么样?
Here is a working and simple jQuery example : http://jsbin.com/isukam/1 这是一个有效且简单的jQuery示例: http : //jsbin.com/isukam/1

Check weather resource for more information. 检查天气资源以获取更多信息。

Disclosure: I own this API. 披露:我拥有此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). Web浏览器会阻止其他域中的内容(因此,如果您位于localhost或www.yoursite.com上,并且正在http://api.worldweatheronline.com上调用Web服务,它将被阻止)。

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. 要确认是这种情况,您可以打开Web浏览器的开发人员工具,并且控制台或网络区域中可能会出现有关跨域调用的错误消息。 (To open the developer tools use Ctrl-Shift-I in Chrome, Ctrl-Shift-K in Firefox and F12 in IE). (要打开开发人员工具,请在Chrome中使用Ctrl-Shift-I,在Firefox中使用Ctrl-Shift-K,在IE中使用F12)。

If the service supports them you can use either JSONP or CORS . 如果服务支持它们,则可以使用JSONPCORS 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). (跨域限制仅是浏览器安全功能,因此您可以从服务器端的ASP.NET,PHP,Java等服务调用该服务,而不会出现问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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