AJAX-CORS 跨域

1、CORS就是一套AJAX跨域问题的解决方案。

2、CORS的原理: CORS定义一种跨域访问的机制,可以让AJAX实现跨域访问。

3、CORS浏览器支持情况:

  Chrome 3+
  Firefox 3.5
  Opera 12+
  Safari 4+
  IE 8+

4、JS-Ajax相关:

ajax({
	url : "XXXX",  // 请求url
	method: options.type, // 请求方式
	data: {"data" : "XXXX"}, //参数
	success: function () {
		//成功
	}
});

function ajax(options) {
	options = options || {};

	options.async = options.async || true;
	
	var params = '';
	for (var item in options.data) {
		params += (item + '=' + options.data[item] + '&');
	}
	if(params != ''){
		params = params.substring(0,params.length - 1);
	}
	
	if (options.method === 'get') {
		options.url += options.url.indexOf('?') == -1 ? '?' + params : params;
	}

	var xhr = createCORSXHR(options.method, options.url); //创建XHR对象
	if(xhr === null){
		console.log("XMLHttpRequest对象创建失败");
		return;
	}
	if (options.method === 'post') {
		//post方式需要自己设置http的请求头,来模仿表单提交。
		//放在open方法之后,send方法之前。
		
		if ("withCredentials" in xhr) {
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
		// 针对IE
		xhr.send(params); //post方式将数据放在send()方法里
	} else {
		xhr.send(); //get方式则填null
	}
	
	xhr.onload = function(){
		options.success(xhr.responseText);
	};
	xhr.onerror = function(){
		log.debug('ajax请求错误!');
	};

}

/**
 * 创建跨域XMLHttpRequest对象
 * @param  {String} method HttpMethod
 * @param  {String} url    链接地址
 * @return {Object}        XMLHttpRequest对象
 */
function createCORSXHR(method, url) {
	var xhr = new XMLHttpRequest();
	if ("withCredentials" in xhr) {
		// 针对Chrome/Safari/Firefox.
		xhr.open(method, url, true);
	} else if (typeof XDomainRequest != "undefined") {
		// 针对IE
		xhr = new XDomainRequest();
		xhr.open(method, url);
	} else {
		// 不支持CORS
		xhr = null;
	}
	return xhr;
}

5、服务端:

// 跨域,只要在请求的接口加上这行代码
response.setHeader("Access-Control-Allow-Origin", "*"); //可以写成配置,指定域名    

  

猜你喜欢

转载自www.cnblogs.com/saint-zhang/p/12068625.html
今日推荐