当前位置: 代码迷 >> Web前端 >> 动态创办script标签跨域请求
  详细解决方案

动态创办script标签跨域请求

热度:115   发布时间:2012-11-06 14:07:00.0
动态创建script标签跨域请求
function load_script(url, callback){
	var head = document.getElementsByTagName('head')[0];
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	//借鉴了jQuery的script跨域方法
	script.onload = script.onreadystatechange = function(){
if((!this.readyState||this.readyState === "loaded"||this.readyState === "complete")){
			callback && callback();
			// Handle memory leak in IE
			script.onload = script.onreadystatechange = null;
			if ( head && script.parentNode ) {
			  head.removeChild( script );
			}
		}
	};
	// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
	head.insertBefore( script, head.firstChild );
}

window.baidu = {sug : function(data){alert(data.s)}};
load_script('http://suggestion.baidu.com/su?wd=w',function(){alert('loaded')});


运行代码测试,返回时json数据格式,也就是为什么动态创建script标签返回的数据格式必须为json格式。返回了一个方法:
window.baidu.sug({q:"w",p:true,s:["wow","wwe","webqq","www.4399.com","www.baidu.com","www.163.com","wow官网","www.qq.com","wonder girls","windows7"]});

也就是在客户端执行定义好的window.baidu.sug方法
  相关解决方案