问题描述
我已经编写了一个Web应用程序,该应用程序在JQuery中使用了很多$.post
调用.现在,我想随它发送withCredentials: true
来保持会话存活,在$.ajax
中看起来像这样(并且也可以这样):
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 session alive, what looks like this in $.ajax
(and also works like this):
$.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)
This is because I would now like to upload the PHP files to my server and export the client side using Cordova. (withCredentials: true
is only included because of testing on my localhost server)Can I pack this into the $.post
call or do I need to replace all calls? (I would write a new function which would look similar to $.post)
推荐答案
您可以使用 jQuery.ajaxSetup()设置每个ajax请求将使用的默认选项(包括$.post
和$.get
)
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');
有关此API的警告
Also the warning regarding this API
jQuery文档中的
from jQuery documentation
这篇关于jQuery $ .post跨域和凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!