jQuery $ .post跨域和凭据 [英] JQuery $.post cross domain and credentials

查看:700
本文介绍了jQuery $ .post跨域和凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个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

注意:此处指定的设置将影响对$ .ajax或$ .ajax的所有调用 基于Ajax的派生类,例如$ .get().这可能会导致不良后果 行为,因为其他调用者(例如插件)可能正在等待 正常的默认设置.因此,我们强烈建议 反对使用此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.

jQuery文档中的

from jQuery documentation

这篇关于jQuery $ .post跨域和凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆