问题 JQuery $ .post跨域和凭据


我写了一个使用了很多的web应用程序 $.post 用JQuery调用。现在我想发送 withCredentials: true 用它来保持会话活着,看起来像这样 $.ajax (也是这样的):

$.ajax({
            type: 'post',
            url: 'http://example.com/server/api.php',
            crossDomain: true,
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            data: {
                username : 'test',
                password : 'test'
            },
            success: function (d) {
                $('body').html(d.status);
            }
        });

这是因为我现在想将PHP文件上传到我的服务器并使用Cordova导出客户端。 (withCredentials: true 仅包含因为我的localhost服务器上的测试 我可以装进去吗 $.post 打电话或我是否需要更换所有电话? (我会写一个类似于$ .post的新函数)


10147
2017-09-24 10:02


起源

问题是?? - iJade
重复: stackoverflow.com/questions/16689496/... - Control Freak
@ZeeTee链接到没有标记正确答案的问题是:P - MoshMage
看看第一个答案,它清楚地显示了答案。 - Control Freak
@ZeeTee这不是重复,因为我想要会话凭据而另一个线程需要基本身份验证 - JSHelp


答案:


您可以使用 jQuery.ajaxSetup() 设置每个ajax请求将使用的默认选项(包括 $.post 和 $.get

$.ajaxSetup({
    crossDomain: true,
    xhrFields: {
        withCredentials: true
    },
    username: 'test',
    password: 'test'
});

$.post('http://example.com/server/api.php', {
    username: 'test',
    password: 'test'
}, function (d) {
    $('body').html(d.status);
}, 'json');

还有关于此API的警告

注意:此处指定的设置将影响对$ .ajax或的所有调用   基于Ajax的衍生产品,例如$ .get()。这可能导致不良后果   因为其他调用者(例如,插件)可能会期待这种行为   正常的默认设置。出于这个原因,我们强烈建议   反对使用此API。相反,在。中明确设置选项   调用或定义一个简单的插件来执行此操作。

来自jQuery文档


15
2017-09-24 10:13



我已经尝试了这个,现在它可以工作,因为我把它放在文件的末尾而不是在开头 - JSHelp