【问题标题】:Cross Domain Javascript/AJAX issue跨域 Javascript/AJAX 问题
【发布时间】:2013-11-15 18:33:09
【问题描述】:

我对调用 API 的下拉选择有疑问。当 URL 具有 www 时,它将允许用户从数据库中进行选择,例如 http://www.staynsurf.com/modules/listing/address_description.php?.... 但如果 URL 没有 www,则会出现错误。 (即http://staynsurf.com/modules/listing/address_description.php?...。)。

<script language="javascript" type="text/javascript">
function getXMLHTTP() {
    var xmlhttp=false;  
    try{
        xmlhttp=new XMLHttpRequest();
    }
    catch(e)    {       
        try{            
            xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e){
            try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e1){
                xmlhttp=false;
            }
        }
    }

    return xmlhttp;
}

function getState(countryId) {      

    var strURL="http://www.staynsurf.com/findState.php?country="+countryId;
    var req = getXMLHTTP();

    if (req) {

        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                // only if "OK"
                if (req.status == 200) {                        
                    document.getElementById('statediv').innerHTML=req.responseText;                     
                } else {
                    alert("There was a problem while using XMLHTTP:\n" + req.statusText);
                }
            }               
        }           
        req.open("GET", strURL, true);
        req.send(null);
    }       
}

【问题讨论】:

    标签: javascript html mysql ajax


    【解决方案1】:

    使用 AJAX 时,调用页面的域和目标 URL 必须相同。 www.stansurf.comstaynsurf.com 不一样(浏览器无法知道您在服务器上已将它们等效)。

    最简单的解决方案是将域排除在目标 URL 之外,因此它会自动使用与调用页面相同的域:

    var strURL="/findState.php?country="+countryId;
    

    【讨论】: