weixin_33691817 2015-08-10 10:31 采纳率: 0%
浏览 753

如何禁用 Ajax 302 重定向?

我必须对Microsoft登录服务(在线共享点)进行POST,该服务会在响应中返回2个cookie,这些cookie可以用于数据请求。

但是,它返回了302(临时移动)消息,并尝试重定向到无效页面,这使ajax请求失败了,并跳至“错误”部分——尽管第一个请求具有有效的和正确使用了我可以使用的响应数据。

function getFedAuthCookies(token)
{
$.support.cors = true; // enable cross-domain query

$.ajax({
    type: 'POST',
    data: token,
    url: "https://mysharepoint.sharepoint.com/_forms/default.aspx?wa=wsignin1.0", //loginUrl,  
    contentType: "application/json;odata=verbose",   //'application/x-www-form-urlencoded',
    dataType: 'json',
    headers: {
        "Accept": "application/json;odata=verbose"
    },   
    // dataType: 'html', // default is OK: Intelligent Guess (xml, json, script, or html)
    success: function (data, textStatus, result) {
        alert("WORKED");
    },
    error: function (result, textStatus, errorThrown) {
        alert("FAILED");
        reportError(result, textStatus, errorThrown);
    }
});

}

这是在浏览器开发者控制台(“网络”面板)中的外观:https://i.stack.imgur.com/sBLi8.png。

如何在第一个具有正确数据和302消息的请求时停止?

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-04 04:45
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    要阻止Ajax 302重定向,请确保您在发送AJAX请求之前检查HTTP状态码。如果收到的状态码不是200(成功),则应该抛出一个异常或采取其他措施来处理这种情况。

    以下是一个示例:

    function getFedAuthCookies(token)
    {
        $.support.cors = true;
    
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'https://mysharepoint.sharepoint.com/_forms/default.aspx?wa=wsignin1.0', true);
    
        xhr.setRequestHeader('Content-Type', 'application/json;odata=verbose');
    
        xhr.onreadystatechange = function() {
            if(xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText); // 输出JSON数据
            } else if(xhr.readyState == 4) {
                if(xhr.status != 200) { // 如果状态码不为200,则捕获异常
                    throw Error('Failed to authenticate');
                }
            }
        };
    
        xhr.send(JSON.stringify({token: token}));
    }
    

    这段代码会创建一个新的XMLHttpRequest对象并设置其类型、URL和头部信息。然后,它将监听onreadystatechange事件以检查状态码。当状态码变为200并且请求已完成时,它将打印响应内容;否则,如果状态码不为200,则捕获异常并抛出错误。

    请注意,这个例子仅适用于服务器端JavaScript环境。如果您正在使用Node.js等后端语言,请查看相应文档以了解如何处理HTTP状态码。

    评论

报告相同问题?