ajax跨域请求
1 跨域问题在一个A.com页面下通过ajax访问B.com的数据,浏览器出于安全考虑的同源策略,会出现数据不可访问的跨域问题
如下面的写法,代码在A.com的页面上,访问B的数据
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /><script type="text/javascript"> function hello(result) { var i='hello world';alert(i); alert(result); } var xmlhttp=new XMLHttpRequest();xmlhttp.open("GET","http://B.com",false);xmlhttp.send();var jsondata=xmlhttp.responseText;hello(jsondata);</script>
var jsondata=xmlhttp.responseText拿不到返回的数据。
2 跨域的解决-动态生成脚本
同源策略不阻止动态脚本的插入,于是可以改写成
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /><script type="text/javascript"> function hello(result) { var i='hello world';alert(i); alert(result); } var JSONP=document.createElement("script"); JSONP.type="text/javascript"; JSONP.src="http://B.com?callback=hello"; document.getElementsByTagName("head").appendChild(JSONP); </script>
提供数据的服务端,需要生成以下规范的html:
$callback($data);
其实也就是一段js脚本语句,函数名为客户端传过来的,data为函数入参。
(引用 http://justcoding.iteye.com/blog/1366102)
页:
[1]