function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && (xmlhttp.status>=200&&xmlhttp.status<=300))
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}else{
alert(xmlhttp.status);
}
}
xmlhttp.open("GET","https://api.shenjian.io/promovie/piaofang?appid=fed023bfdffa5202e08665601d127045/",true);
xmlhttp.send(null);
}
第一次写这个,请大佬看一下问题出在哪里?
用jQ封装的ajax,在把datatype从JOSN改成JSONP就可以成功获取数据,但是想用原生的方法实现一下,发现问题还是挺大的
var url="https://api.shenjian.io/promovie/piaofang?appid=fed023bfdffa5202e08665601d127045";
//创建xhr对象
function createCORSXhr(url,method){
var xhr=new XMLHttpRequest();
if("withCredentials" in xhr){
xhr.open(method,url,true);
}else if(typeof XDomainRequest !=="undefined"){
xhr=new XDomainRequest();
xhr.open(method,url);
}else
xhr=null;
return xhr;
}
//创建ajax请求
function sendAjaxRequest(){
var xhr=createCORSXhr(url,"get");
//xhr.setRequestHeader("Origin","https://api.shenjian.io/promovie/piaofang?appid=fed023bfdffa5202e08665601d127045")
xhr.οnlοad=function(){
if(xhr.readyState==4){
if(xhr.status>=200 && xhr.status<300 || xhr.status==304)
alert(xhr.responseText);
}else{
alert(" ajax error...")
}
}
};
xhr.οnerrοr=function(){
alert("error code:"+xhr.status)
}
xhr.send(null);
};
sendAjaxRequest()
网上看到有人这么写,他说他这样可以支持跨域,但是我尝试了一下报的是一样的错