首先解释一下跨域定义:在A网站中,希望使用Ajax来获得B网站中的特定内容。如果A网站与B网站不在同一个域中,那么就出现跨域访问问题。
:在A网站中,希望使用Ajax来获得B网站中的特定内容。如果A网站与B网站不在同一个域中,那么就出现跨域访问问题。
出现跨域问题时,在console里面会有如下提示信息:“XMLHttpRequest cannot load http:-------- not allowed by Access-Control-Allow-Origin.”
解决跨域方法:在$.ajax()添加 xhrFields:{ withCredentials:true}, crossDomain:true,
$.ajax()添加 xhrFields:{ withCredentials:true}, crossDomain:true,
function request(url,data,success_callback){ $.ajax({ //提交数据的类型 POST GET type:"POST", //提交的网址 url:url, //提交的数据 data:data, //返回数据的格式 datatype: "json",//"xml", "html", "script", "json", "jsonp", "text". xhrFields:{ withCredentials:true }, crossDomain:true, //在请求之前调用的函数 beforeSend:function(){ }, //成功返回之后调用的函数 success:function(response){ if (response == null) { console.log("response is null"); return; } response=eval("("+response+")"); //解析json数据 if (response.status == "2") { console.log("success"); success_callback(response); }else{ alert(response.msg); } }, //调用执行后调用的函数 complete: function(XMLHttpRequest, textStatus){ // alert(XMLHttpRequest.responseText); // alert(textStatus); //HideLoading(); }, //调用出错执行的函数 error: function(){ //请求出错处理 console.log("error"); } });
xhrFields:{ withCredentials:true }, crossDomain:true, //在请求之前调用的函数 beforeSend:function(){ }, //成功返回之后调用的函数 success:function(response){ if (response == null) { console.log("response is null"); return; } response=eval("("+response+")"); //解析json数据 if (response.status == "2") { console.log("success"); success_callback(response); }else{ alert(response.msg); } }, //调用执行后调用的函数 complete: function(XMLHttpRequest, textStatus){ // alert(XMLHttpRequest.responseText); // alert(textStatus); //HideLoading(); }, //调用出错执行的函数 error: function(){ //请求出错处理 console.log("error"); } });
}