ajax和jsonp

属性

  • readyState
    1. 0 : 已经新建xhr对象
    2. 1 : open方法调用了
    3. 2 : send方法调用了
    4. 3 : http响应头信息已经接收,但没有接受完成
    5. 4 : 接收完成。
  • responseText : 服务器响应的文本内容
  • Status: 服务器返回的http状态码。
  • Onreadystatechange:请求状态改变的事件触发器。

方法

  • open(method, url, asynch, userName, password) 指定和服务器端交互的HTTP方法
    1. method: get/post等。http请求的方式
    2. url : 请求的服务器的地址。
    3. asynch: true/false, 是否设为异步请求,一般为true
    4. useeName和password: 提供http认证机制需要的用户名和密码
  • send(content) 向服务器发送请求,
    1. content: content可以指定为null表示不发送数据,其内容可以是DOM对象,输入流或字符串。 get方法时不用发送数据。
  • SetRequestHeader(String header,String Value) 设置请求头。
  • getAllResponseHeaders() 返回响应头的所有信息,返回值是一个字符串
  • getResponseHeader(String header) 返回HTTP响应头中指定的键名header对应的值
  • abort() 停止 http请求

ajax

//options:url,type,data,success,error,timeout
function ajax(options){
	
	options = options || {};
	if(!options.url){
		return;
	}
	
	options.type = options.type || "get";
	options.data = options.data || {};
	options.timeout = options.timeout || 0;
	
	var str = json2url(options.data);
	
	//1 创建
	if(window.XMLHttpRequest){
		var xhr = new XMLHttpRequest();
	} else {
		var xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if(options.type == "get"){
		//2 连接
		xhr.open("get",options.url + "?" + str,true);
		//3 发送
		xhr.send();
	} else {
		//2 连接
		xhr.open("post",options.url,true);
		xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		//3 发送
		xhr.send(str);
	}
 	
	//4 接收
	xhr.onreadystatechange = function(){
		if(xhr.readyState == 4){
			clearTimeout(timer);
			if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
				options.success && options.success(xhr.responseText);
			} else {
				options.error && options.error(xhr.status);
			}
		}	
	};
	
	if(options.timeout){
		var timer = setTimeout(function(){
			//终止ajax请求 
			//abort
			alert("超时");
			xhr.abort();
				
		},options.timeout);
	}
	
	function json2url(json){
		var arr = [];
		json.t = Math.random();
		for(var name in json){
			arr.push(name + "=" + encodeURIComponent(json[name]));
		}
	return arr.join("&");
	}
}

jsonp

同源: 协议相同,域名相同, 端口相同
jsonp解决ajax不能跨域的问题,原理script标签的src可以是url地址,浏览器解析文件与后缀名无关。当script引入完成,里面的内容是执行一个函数,服务器会把数据放入到函数的参数中,这个函数需要事先创建并挂载在本地上,

/**
 * optinos
 *    url :
 *    data : {}
 *    cbName : 回调函数的名字
 *    success: 成功的函数
 *    error: 错误的函数
 *    timeout: 超时设置
 * @param {any} options
 */
function jsonp(options){
  options = options || {};

  if(!options.url) return;
  options.data = options.data || {};
  options.cbName = options.cbName || "cb";
  options.timeout = options.timeout || 0;

  let fnName = ("jsonp_" + Math.random()).replace(".","");

  let arr = [];
  options.data[options.cbName] = fnName;
  for(let name in options.data){
    arr.push(name + "=" + encodeURIComponent(options.data[name]));
  }
  let str = arr.join("&");

  //2 全局函数
  window[fnName] = function(json){
    options.success && options.success(json);
    window[fnName] = null;
    oHead.removeChild(oS);
    clearTimeout(timer);
  };

  //1 创建script
  let oS = document.createElement("script");
  oS.src = options.url + "?" + str;
  let oHead = document.getElementsByTagName("head")[0];
  oHead.appendChild(oS);

  if(options.timeout){
    let timer = setTimeout(function(){
      options.error && options.error();
      window[fnName] = function(){};
      oHead.removeChild(oS);
    },options.timeout);
  }
}
posted @ 2017-08-03 16:39  ding0304  阅读(190)  评论(0)    收藏  举报