解决Json数据跨域问题

Json跨域获取数据。很多人在用jQuery的getJSON(“xxx”)发现获取不到数据,纠结了很久才发现是跨域问题  今天来分享一下我是怎么解决Json数据跨域问题的

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>Json跨域解决办法</title>
 5     <script src='http://code.jquery.com/jquery-1.8.0.js' type='text/javascript'></script>
 6     <script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script>
 7 </head>
 8 <body>
 9     <div id="content">
10     </div>
11     <script>
12         $(function () {
13             $.getJSON("http://query.yahooapis.com/v1/public/yql", {
14                 q: "select * from json where url=\"http://m.weather.com.cn/data/101010100.html\"",
15                 format: "json"
16             }, function (data) {
17                 if (data.query.results) {
18                     $("#content").text(JSON.stringify(data.query.results));
19                     var J_data = JSON.parse(JSON.stringify(data.query.results));
20                     alert(J_data.weatherinfo.city);
21 
22                 } else {
23                     $("#content").text('no such code: ' + code);
24                 }
25             });
26         });
27     </script>
28 </body>
29 </html>

上面是 http://m.weather.com.cn/data/101010100.html气象局返回的Json 而我们在直接用

$.getJSON("http://m.weather.com.cn/data/101010100.html", function (data) {
  //
});

会发现浏览器控制台提示这样的错误 :

 

我这里用到的是YQL来解决跨域问题的  

$("#content").text(JSON.stringify(data.query.results)); 在这里是把json对象转换为字符串,因为是字符串所以我们取不到json数据里面的值 我们可以通过JSON.parse()的方法对文本数据转换生成json数据结构

通过添加断点调试可以看到J_data是什么 

  看到这里我们就不难取到下面的值了 完美解决问题.

 

 

很多人不知道json2怎么用 我在这里给出一个json2的学习连接 http://www.cnblogs.com/beijia/archive/2011/10/05/json2.html

里面有详细介绍  希望有帮助到大家~!

转载于:https://www.cnblogs.com/SoraAoi/archive/2013/04/11/3013572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值