js ajax请求

js ajax请求

原生 js ajax请求(兼容ie6)

    var xhr = null;
    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
	 }else{ // 为了兼容IE6
        xhr = new ActiveXObject("Microsoft.XMLHTTP") 
	 }
	 xhr.open('GET', url, true); // get , 路径 ,异步
	// 添加http头,发送信息至服务器时内容编码类型(请求方式为post)
    // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); 
	 xhr.send(JSON.stringify(obj));  // 发送请求 要发送的参数,要转化为json字符串发送给后端,后端就会接受到json对象
     xhr.onreadystatechange = function() {
      //  说明请求已完成   200成功  304未修改
      if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { 
        // 从服务器获得数据 
        console.log(xhr.responseText)
      }
    }

你可能感兴趣的:(ajax请求)