前端技术

当前位置:首页 > 前端技术 >

js跨域及解决方法

时间:2015-06-03        阅读:次        QQ群:182913345

1.什么是跨域
我们经常会在页面上使用ajax请求访问其他服务器的数据,此时,客户端会出现跨域问题.
跨域问题是由于javascript语言安全限制中的同源策略造成的.
简单来说,同源策略是指一段脚本只能读取来自同一来源的窗口和文档的属性,这里的同一来源指的是主机名、协议和端口号的组合.
 
js跨域及解决方法
 
2.实现原理
在HTML DOM中,Script标签是可以跨域访问服务器上的数据的.因此,可以指定script的src属性为跨域的url,从而实现跨域访问.
 
3.解决方案
方案一
服务器端:
 
protected void Page_Load(object sender, EventArgs e){
	string result = "callback({\"name\":\"zhangsan\",\"date\":\"2012-12-03\"})";
	Response.Clear();
	Response.Write(result);
	Response.End();
}

客户端:
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title></title>
		<script type="text/javascript">
			var result = null;
			window.onload = function () {
				var script = document.createElement("script");
				script.type = "text/javascript";
				script.src = "http://192.168.0.101/ExampleBusinessApplication.Web/web2.aspx";
				var head = document.getElementsByTagName("head")[0];
				head.insertBefore(script, head.firstChild);
			};
			
			function callback(data) {
				result = data;
			}

			function b_click() {
				alert(result.name);
			}
		</script>
	</head>
	<body>
		<input type="button" value="click me!" onclick="b_click();" />
	</body>
</html>

方案二,通过jquery来完成
通过jquery的jsonp的方式.使用此方式,对服务器端有要求.
服务器端:
 
protected void Page_Load(object sender, EventArgs e){
	string callback = Request.QueryString["jsoncallback"];
	string result = callback + "({\"name\":\"zhangsan\",\"date\":\"2012-12-03\"})";
	Response.Clear();
	Response.Write(result);
	Response.End();
}

客户端:

$.ajax({
	async: false,
	url: "http://192.168.0.5/Web/web1.aspx",
	type: "GET",
	dataType: 'jsonp',
	//jsonp的值自定义,如果使用jsoncallback,那么服务器端,要返回一个jsoncallback的值对应的对象.
	jsonp: 'jsoncallback',
	//要传递的参数,没有传参时,也一定要写上
	data: null,
	timeout: 5000,
	//返回Json类型
	contentType: "application/json;utf-8",
	//服务器段返回的对象包含name,data属性.
	success: function (result) {
		alert(result.date);
	},
	error: function (jqXHR, textStatus, errorThrown) {
		alert(textStatus);
	}
});

上一篇:js数组操作

下一篇:jQuery 解析Json字符串

扫一扫,更多精彩内容推送

PHP技术分享

分享PHP技术,前端技术,数据库,SEO优化,服务器,网络安全等知识,是php程序员工作学习的好帮手!

Copyright © 2013-2015.PHP技术分享 www.php520.cn  版权所有  网站地图    PHP学习交流群

免责声明:网站内容收集于互联网,本网站不承担任何由于内容的合法性及健康性所引起的争议和法律责任。

欢迎大家对网站内容侵犯版权等不合法和不健康行为进行监督和举报。 沪ICP备15014499号-2