使用jQuery-AJAX–读取获得跨域JSONP数据的示例

时间:2023-03-09 05:57:36
使用jQuery-AJAX–读取获得跨域JSONP数据的示例

在项目开发中,如果在同一个域名下就不存在跨域情况,使用$.getJSON()即可实现。但是需要跨域请求其他域名下面的Json数据就需要JSONP的方式去请求,跨域写法和getJSON有差异。如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>使用jQuery-AJAX--读取获得跨域JSONP数据</title>
<script src="./jquery-1.7.2.js" type="text/javascript"></script>
<style type="text/css">
body,html{font-family: "Microsoft Yahei";}
a{text-decoration: none;}
</style>
</head>
<body>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<h2><a href="javascript:void(0)" class="btnAJAX">点击AJAX获取数据JSONP跨域....</a></h2>
<script type="text/javascript">
$(function() {
$(".btnAJAX").click(function(){
$.ajax({
type : "get",
async:false,
url : "http://weather.123.duba.net/static/weather_info/101121301.html",
dataType : "jsonp",
jsonp: "callbackparam", //服务端用于接收callback调用的function名的参数
jsonpCallback:"weather_callback", //callback的function名称
success : function(json){
// console.log(json); //浏览器调试的时候用
alert(json.weatherinfo.city);
alert(json.weatherinfo.week);
alert(json.update_time);
},
error:function(){
alert('fail');
}
});
}); });
</script> </body>
</html>