文章详细
解决Json数据跨域问题
 2013/4/12 10:09:24 评论:0人 阅读次数:6994

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
     <title>Json跨域解决办法</title>
     <script src="http://code.jquery.com/jquery-1.8.0.js" type="text/javascript"></script>
 </head>
 <body>
     <div id="content">
     </div>
     <script>
         $(function () {
             $.getJSON("http://query.yahooapis.com/v1/public/yql", {
                 q: "select * from json where url=\"http://m.weather.com.cn/data/101010100.html\"",
                 format: "json"
             }, function (data) {
                 if (data.query.results) {
                     $("#content").text(JSON.stringify(data.query.results));
                     var J_data = JSON.parse(JSON.stringify(data.query.results));
                     alert(J_data.weatherinfo.city);
 
                 } else {
                     $("#content").text("no such code: " + code);
                 }
             });
         });
     </script>
 </body>
 </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

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

如需转载请注明出处:http://www.86y.org/art_detail.aspx?id=548【解决Json数据跨域问题】幸凡学习网
0
 
相关文章
推荐文章
Created By Charry-May 3,2010
粤ICP备10093478号-1
顶部