JQuery $.post cross domain and credentials

前端 未结 1 1270
花落未央
花落未央 2021-02-05 21:00

I have written a web application which uses lot\'s of $.post calls with JQuery. Now I would like to send withCredentials: true with it to keep a sessio

相关标签:
1条回答
  • 2021-02-05 21:28

    You can use jQuery.ajaxSetup() to set default options that each ajax request will use (including $.post and $.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');
    

    Also the warning regarding this API

    Note: The settings specified here will affect all calls to $.ajax or Ajax-based derivatives such as $.get(). This can cause undesirable behavior since other callers (for example, plugins) may be expecting the normal default settings. For that reason we strongly recommend against using this API. Instead, set the options explicitly in the call or define a simple plugin to do so.

    from jQuery documentation

    0 讨论(0)
提交回复
热议问题