JQuery $ .post跨域和凭据

我编写了一个Web应用程序,它使用了许多带有JQuery的$.post调用。 现在我想发送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仅包含因为在我的本地主机服务器上进行测试而包含的内容)我可以将其打包到$.post调用中,还是需要替换所有调用? (我会写一个类似于$ .post的新函数)

您可以使用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文档