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
里面有详细介绍 希望有帮助到大家~!