【前端】 发送http请求 ajax 跨域

版权声明:高性能MySQL是第3版,注意mysql版本;很多博客都参考或者直接转载自网络,如果不方便被转载,看到请与我联系 https://blog.csdn.net/ma15732625261/article/details/82226762

ajax重定向跨域问题

请求到后端,后端接口重定向到另一个域名地址:跨域问题

ajax:无刷新,重定向时,ajax获取重定向状态值30*和url,再获取重定向页面运行完后输出到客户端的html代码,返回200

    请求后端接口,后端返回302和一个url,ajax据http的code码再一次发起请求,去请求 服务器端302返回的url,此时跨域了

    解决:在第一次得到相应处理后js做一次location.href跳转:让浏览器去请求重定向的接口而不是ajax

浏览器:通过返回的http状态进行相应操作,如访问一个页面,页面重定向时浏览器获取302 标示,将地址栏url换成后端返回的url,重定向后的url进行转向

https://blog.csdn.net/liyantianmin/article/details/73485545

原生js

获取XMLHttpRequest对象


function createXMLHttpRequest() {
	var xmlHttp;
	if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
		if (xmlHttp.overrideMimeType)
			xmlHttp.overrideMimeType('text/xml');
	} else if (window.ActiveXObject) {
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
			}
		}
	}
	return xmlHttp;
}

 

get请求:XMLHttpRequest

<script type="text/javascript"> 
/* 创建 XMLHttpRequest 对象 */
var xmlHttp; 
function GetXmlHttpObject(){ 
  if (window.XMLHttpRequest){ 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
  }else{// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
  } 
  return xmlhttp; 
} 
// -----------ajax方法-----------// 
function getLabelsGet(){ 
  xmlHttp=GetXmlHttpObject(); 
  if (xmlHttp==null){ 
    alert('您的浏览器不支持AJAX!'); 
    return; 
  } 
  var id = document.getElementById('id').value; 
  var url="http://www.Leefrom.com?id="+id+"&t/"+Math.random(); 
  xmlHttp.open("GET",url,true); // 异步处理返回
  xmlHttp.onreadystatechange=favorOK;//发送事件后,收到信息了调用函数 
  xmlHttp.send(); 
}
function getOkGet(){ //代码没用到吧?
  if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){ 
    // 本地提示:加载中 
  } 
  if (xmlHttp.readyState==4 && xmlHttp.status==200){ 
    var d= xmlHttp.responseText; 
    // 处理返回结果 
  } 
} 
</script>

post:XMLHttpRequest

基本上同get
xmlhttp.open("POST",url,true); 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send(); 

https://www.jb51.net/article/86157.htm

https://blog.csdn.net/smst1987/article/details/6735067

    XMLHttpRequest 是 AJAX 的基础,在创建 XMLHttpRequest 对象时,必须与你写的ajax方法在同一个‘<script></script>'标签中!否则ajax请求会出错,并无法返回数据。 javascript/js的ajax的POST/GET请求

简单来说:

 var xmlhttp=new XMLHttpRequest();
    var url="/space-uid-"+i+".html";
    console.log('visit',url);
    i++;
    xmlhttp.open("GET",url,true); //第三个参数是同步异步,主线程只能异步
    xmlhttp.send();

 

较为完整的一个流程:get【

jQuery:先引入js【

$.get();
$.post();

//example
var params = {id:1,name:'tom'};
url = '/test_post.php';
$.post(url,params,function(data){
    alert(data);//这个data就是test_post.php返回的数据
});


 

猜你喜欢

转载自blog.csdn.net/ma15732625261/article/details/82226762