jQuery getJSON doesnt send cookies

前端 未结 3 1867
半阙折子戏
半阙折子戏 2020-12-28 21:54

i am including JS on domain1 form domain2


t

3条回答
  •  我在风中等你
    2020-12-28 22:30

    If you want to use AJAX petitions over different domains/subdomains you have to implement Cross Origin Requests.

    References:

    • http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
    • https://developer.mozilla.org/en/http_access_control

    Examples:

    • http://arunranga.com/examples/access-control/

    Your server needs to send this headers:

    • Access-Control-Allow-Origin: test1.floowie.com
    • Access-Control-Allow-Credentials: true // allow cookie/session credentials
    • Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS

    You can return the Access-Control-Allow-Origin globally or set specifically dependent of your input Origin ($_SERVER['HTTP_ORIGIN']) request header. Also apply for Access-Control-Allow-Methods.

    You must implement the OPTIONS petition. Before the first AJAX call, modern browsers call that URL with an OPTIONS method to retrieve the above headers.

    Ok this is the first part, the second is with jQuery. Read very carefully this page: http://api.jquery.com/jQuery.ajax/

    You will need to add some options to every AJAX call, you can do it globally:

    $(document).ajaxSend(function (event, xhr, settings) {
        settings.xhrFields = {
            withCredentials: true
        };
    });
    

    Or specific:

    $.ajax({
        url: a_cross_domain_url,
        xhrFields: {
            withCredentials: true
        }
    });
    

    This issue made ​​me lose many hours... hope it helps.

    Note that you won't need to set your cookie domain as ".floowie.com" if you want.

提交回复
热议问题