使用jquery的AJAX方法请求数据JSONP跨域的示例DEMO

  •   
  • 4158
  • jQuery
  • 6
  • super_dodo
  • 2015/03/09

很多时候都是在一个域名下面做操作或者请求以及ajax的方法进行。所以$.getJSON一般情况下都够用了。协助上使用curl也就差不多了。但是当简单的且不在一个域名下面的直接去请求数据,就会遇到请求不成功的时候。自己用惯了getJSON居然无从下手了。此处贴出一个小demo以备学习和观摩。

请求的地址为一个中国天气的api接口。http://weather.123.duba.net/static/weather_info/101121301.html
请求的文件为本地文件。只有jquery和html

直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>jquery-AJAX-DEMO--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>

命是弱者的借口,运是强者的谦辞.....