1. 前言
在进行网站开发的过程中经常会用到第三方的数据,但是由于同源策略的限制导致ajax不能发送请求,因此也无法获得数据。解决ajax的跨域问题可以使用jsonp技术
2.代码
<!DOCTYPE html>
<html>
<head>
<title>weatherSample</title>
<script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //init, default: XiaMen
getWeatherInfo();
$("#cityName").text("城市: 厦门"); var tableHeaderData = $('table').parent().html(); function getWeatherInfo(){ $.ajax({
type : "get",
async: false,
url : "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8",
data:{
location:$("#city").val()||"厦门"
},
dataType: "jsonp",
jsonp:"callback", //请求php的参数名
jsonpCallback: "jsonhandle",//要执行的回调函数
success : function(data) { if(data.status == 'success'){ $('#tip').html(""); var list = data.results;
var weatherDataArr = list[0].weather_data;
var items = ""; //init table of weatherInfo, just stay header data
$('table').html(tableHeaderData); for(var i=0 ; i< weatherDataArr.length ;i++){
var date = weatherDataArr[i].date;
var dayPictureUrl = weatherDataArr[i].dayPictureUrl;
var nightPictureUrl = weatherDataArr[i].nightPictureUrl;
var temperature = weatherDataArr[i].temperature;
var weather = weatherDataArr[i].weather;
var wind = weatherDataArr[i].wind; var item = "<tr><td>"+date+"</td>"
+ "<td><img src='"+dayPictureUrl+"'/></td>"
+ "<td><img src='"+nightPictureUrl+"'/></td>"
+ "<td>"+temperature+"</td>"
+ "<td>"+weather+"</td>"
+ "<td>"+wind+"</td>"
+ "</tr>"; items+=item; } $('table tr').after(items);
} },
error:function(data){
//获取失败,打印出原因
$('#tip').html(`error reason=>{"status":220,"message":"APP Referer校验失败"}`)
} });
} $("button").click(function(){
getWeatherInfo();
}) $("input").change(function(){
$("#cityName").text("城市: " + $('#city').val());
}) });
</script>
</head>
<body>
<div style="margin-bottom:10px">
<input type="text" id="city" name="city"/>
<button style="margin-left:10px">天气查询</button>
</div>
<div id="cityName" style="margin-bottom:10px">城市: </div>
<div>
<table border="1px">
<tr>
<th>日期</th>
<th>白天</th>
<th>晚上</th>
<th>温度</th>
<th>天气</th>
<th>风力</th>
</tr>
</table>
</div>
<div id="tip" style="margin-bottom:10px"></div>
</body>
</html>
注:请求ak已失效
3.功能与效果
3.1 功能
首次加载,默认是厦门的天气预报,输入城市名并点击天气查询按钮则获取该天气的天气预报
3.2 效果图
4.说明
向百度天气服务器发送请求的参数是:output=json&ak=6tYzTvGZSOpYB5Oc2YGGOKt8&callback=jsonhandle&location=%E5%8E%A6%E9%97%A8&_=1507712014958, %E5%8E%A6%E9%97%A8是厦门的utf-8编码加%组成,好奇宝宝点这里
ajax返回来的data如下:
5.参考
2.简单透彻理解JSONP原理及使用(讲得很通俗易懂)