2016-02-25 34 views
0

您好我想從服務器1做Ajax請求到服務器2的JavaScript Ajax代碼:從服務器1中的JavaScript執行阿賈克斯服務器2

function sendGet(path) { 
    var xmlhttp; 
    if(window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } else { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
      return(xmlhttp.responseText); 
     } 
    }; 
    xmlhttp.open("GET", path, true); 
    xmlhttp.send(); 
} 

鉻回報: XMLHttpRequest cannot load http://itaysharon.esy.es/jsdb.php?user=test&pass=1234. No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'null' is therefore not allowed access. 我使用純JS和我想保持這種方式。 有什麼方法可以解決它在JS? THX

+1

是在服務器中啓用CORS 2? – mido

+0

不,我猜不是 –

+0

你有兩臺服務器嗎?你是否允許在兩端編輯文件? –

回答

1

只需在服務器端的下方添加AJAX請求頭在跨域共享數據

Access-Control-Allow-Origin: * 

OR

Access-Control-Allow-Origin: <server1 IP or domain name> 

對於你的問題

function sendGet(path) { 
    var xmlhttp; 
    xmlhttp.setRequestHeader("Origin","your server ip or domain of client server"); 
    xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*"); 
    if(window.XMLHttpRequest) { 
     xmlhttp = new XMLHttpRequest(); 
    } else { 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if(xmlhttp.readyState === 4 && xmlhttp.status === 200) { 
      return(xmlhttp.responseText); 
     } 
    }; 
    xmlhttp.open("GET", path, true); 
    xmlhttp.send(); 
} 
+0

你能用你的答案編輯我的Ajax代碼嗎? –

+0

你肯定...... ...... –

+1

function sendGet(path){ var xmlhttp; xmlhttp.setRequestHeader(「Origin」,「您的服務器IP或客戶端服務器的域名」); xmlhttp.setRequestHeader(「Access-Control-Allow-Origin」,「*」);如果(window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();如果(window.XMLHttpRequest){xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject(「Microsoft.XMLHTTP」); (xmlhttp.readyState === 4 && xmlhttp.status === 200){ return(xmlhttp.responseText);這個函數返回(xmlhttp.responseText)。 } }; xmlhttp.open(「GET」,path,true); xmlhttp.send(); } –

相關問題