网页中如何读取ajax返回的天气预报json数据
网页中如何读取天气预报返回的json数据读取不到http://m.weather.com.cn/data/101010100.html页面的json数据...
网页中如何读取天气预报返回的json数据
读取不到http://m.weather.com.cn/data/101010100.html 页面的json数据 展开
读取不到http://m.weather.com.cn/data/101010100.html 页面的json数据 展开
2个回答
展开全部
我之前也弄过天气预报的接口,用ajax来读取。
因为涉及到不在同一个域的问题,所以要用jsonp的形式,但是他们没有提供回调的方法,只给了一个链接,所以前端直接好像不是很好获取(可能是我不知道怎么获取)。
后来我在服务器端先把数据获取了,然后在同域下用ajax来请求数据就好。
php代码(xhr2.php):
<?php
header("content-type: text/html");
$url = 'http://m.weather.com.cn/data/';
$id = $_GET['id'];
//$id =101010100;
$data = file_get_contents($url . $id .'.html');
echo $data;
?>
前端用ajax请求xhr2.php:
$.ajax({
url:'xhr2.php',
dataType:"json",
success:dada,
error: function(){
//alert("ERROR!")
}
success: function(msg){
//alert( msg);
}
});
希望能帮到你,如果有更好的方法,我们可以一起交流。
展开全部
$(document).ready(function() {
// 天气
$.getJSON("http://query.yahooapis.com/v1/public/yql", {
q: "select * from json where url=\"http://m.weather.com.cn/atad/101190101.html\"",
format: "json"
}, function(data) {
var $content = $("#content")
if (data.query.results) {
var weatherinfo = data.query.results.weatherinfo;
//console.log(weatherinfo);
var week = ["星期一","星期二","星期三","星期四","星期五","星期六","星期天","星期一","星期二"];
var week_tomorrow ="";
var week_tdat ="";
var week_today = weatherinfo.week;
var index = $.inArray(week_today,week);
week_tomorrow = week[index+1];
week_tdat = week[index+2];
$(".today .location").text(weatherinfo.city);
} else {
$(".today p:eq(1)").text("获取数据失败");
}
});
// 天气
$.getJSON("http://query.yahooapis.com/v1/public/yql", {
q: "select * from json where url=\"http://m.weather.com.cn/atad/101190101.html\"",
format: "json"
}, function(data) {
var $content = $("#content")
if (data.query.results) {
var weatherinfo = data.query.results.weatherinfo;
//console.log(weatherinfo);
var week = ["星期一","星期二","星期三","星期四","星期五","星期六","星期天","星期一","星期二"];
var week_tomorrow ="";
var week_tdat ="";
var week_today = weatherinfo.week;
var index = $.inArray(week_today,week);
week_tomorrow = week[index+1];
week_tdat = week[index+2];
$(".today .location").text(weatherinfo.city);
} else {
$(".today p:eq(1)").text("获取数据失败");
}
});
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询