如何通过ajax执行post操作时克服CORS重定向问题?

时间:2016-06-01 06:54:06

标签: javascript php ajax cors

我可以通过外部登录表单中的post方法类型的表单提交登录到roundcube实例(托管在另一台服务器上)。

我收到此错误(通过ajax签名时):

XMLHttpRequest无法加载https://192.168.0.7/mail/。该请求已重定向到“https://192.168.0.7/mail/?_task=mail&_token=36e97d50951472c4c65de562a0109e94”,对于需要预检的跨源请求,该请求不被允许。

$.ajax({
    type: 'POST',
    url: 'https://192.168.0.7/mail/',
    data: {
        _user: 'myusername', _pass:'mypassword', _autologin: 1, _action: 'login',_task: 'login'
    },
    success: function( data ){
        $('#result').html(data);
    },
    crossDomain: true,
});

我已经克服了除此之外的所有CORS相关问题。我知道在跨站点禁止重定向是默认的浏览器行为。请建议,如果有办法解决这个问题,或者我应该继续寻找其他方法吗?

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用

在服务器中启用跨域请求
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST'); 

答案 1 :(得分:0)

你应该试试这个:

require(data.table)
d1 <- data.frame(index = c(1,2,3,4), location = c('barn', 'house', 'restaurant', 'tomb'), random = c(5,3,2,1), different_col1 = c(66,33,22,11))
d2 <- data.frame(index = c(1,2,3,4), location = c('server', 'computer', 'home', 'dictionary'), random = c(1,7,2,9), differen_col2 = c('hi', 'there', 'different', 'column'))

mydata <- data.table(src = c('one', 'one', 'two', 'one', 'two'), index = c(1,4,2,3,2))

mydata.d1       <- mydata[mydata$src == "one",]
mydata.d2       <- mydata[mydata$src == "two",]

mydata.d1 <- merge(mydata.d1, d1, all.x = T, by = "index")
mydata.d2 <- merge(mydata.d2, d2, all.x = T, by = "index")

# If you want to keep the 'different column' values from d1 and d2:
mydata <- rbind(mydata.d1, mydata.d2, fill = T)
mydata

   index src   location random different_col1 differen_col2
1:     1 one       barn      5             66            NA
2:     3 one restaurant      2             22            NA
3:     4 one       tomb      1             11            NA
4:     2 two   computer      7             NA         there
5:     2 two   computer      7             NA         there

# If you don't want to keep those 'different column' values:
mydata <- rbind(mydata.d1[,.(index, src, location)], mydata.d2[,.(index, src, location)])

mydata

   index src   location
1:     1 one       barn
2:     3 one restaurant
3:     4 one       tomb
4:     2 two   computer
5:     2 two   computer

您应该在标题中添加您需要访问的所有方法。