日期:2014-05-17  浏览次数:20487 次

使用cors跨域,请指教
// 创建XHR对象
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // 针对Chrome/Safari/Firefox.
        xhr.open(method, url, true);
        alert(1);
    } else if (typeof XDomainRequest != "undefined") {
        // 针对IE
        xhr = new XDomainRequest();
        xhr.open(method, url);
        alert(2);
    } else {
        // 不支持CORS
        xhr = null;
        alert(3);
    }
    return xhr;
}

// 辅助函数,用于解析返回的内容
function getTitle(text) {
    return text.match('<title>(.*)?</title>')[1];
}

// 发送CORS请求
function makeCorsRequest() {
    // bibliographica.org是支持CORS的
    var code = $("#code0").val();
    var url = 'http://119.145.12.180/anta/Service/GetFlowcodeInfo?flowcode=' + code;
    var xhr = createCORSRequest('GET', url);
    alert(xhr);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }
    // 回应处理
    xhr.onload = function () {//无法执行成功的回应处理
        var text = xhr.responseText;
        alert(text);
        var title = getTitle(text);
        alert('Response from CORS request to ' + url + ': ' + title);
    };
    xhr.onerror = function () {
        alert('Woops, there was an error making the request.');
    };
    xhr.send();
}
回应处理的时候执行的是onerror,不执行onload。请告诉这是什么原因已经解决的方法

------解决方案--------------------
GetFlowcodeInfo要设置Access-Control-Allow-Origin响应头为你允许跨域的请求的域名,要不也无法实现实现跨域