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")[0].appendChild(JSONP);
</script>提供数据的服务端,需要生成以下规范的html:
$callback($data);
其实也就是一段js脚本语句,函数名为客户端传过来的,data为函数入参。
相关推荐
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
lyqdanang 2020-08-16
curiousL 2020-08-03
时光如瑾雨微凉 2020-07-19
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07
李永毅 2020-07-05
坚持着执着 2020-07-05