跨源请求已阻止:同源策略禁止在某个URI上读取远程资源

时间:2016-11-30 17:37:09

标签: jquery ajax cors cross-domain

我在ajax请求后写了这个:

$.ajax({    
    type : "POST",
    processData:false,        
    crossDomain:true,
    crossOrigin:true,
    contentType:false,          
    headers: { 
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "POST",
        "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",   
    },
    url : 'my URI',
    data: formData,
    success : function(receivedData) {
        console.log("SUCCESS: ");
        alert(receivedData);
    }
});

但是在回复中我通过浏览器收到以下消息: 跨源请求已阻止:同源策略禁止在我的URI上读取远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin'。

1 个答案:

答案 0 :(得分:-1)

尝试以下代码,如果它不起作用,那么你需要实现服务器端cors启用

$.ajax({    
        type : "POST",
        processData:false,

        crossDomain:true,
        crossOrigin:true,
        contentType:false,
        'Access-Control-Allow-Methods': 'POST',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',   
        },
        header:{'Access-Control-Allow-Origin': '*'},
        url : 'my URI',
        data: formData,
        success : function(receivedData) {
            console.log("SUCCESS: ");
            alert(receivedData);

            }

});

然后你可以像这样使用ajax调用

$.ajax({
        url: 'http:ww.abc.com?callback=?',
        dataType: 'JSONP',
        jsonpCallback: 'callbackFnc',
        type: 'GET',
        async: false,
        crossDomain: true,
        success: function () { },
        failure: function () { },
        complete: function (data) {
            if (data.readyState == '4' && data.status == '200') {
                errorLog.push({ IP: Host, Status: 'SUCCESS' })
            }
            else {
                errorLog.push({ IP: Host, Status: 'FAIL' })
            }
        }
});