[jQuery] AJAX跨網域 | AJAX Cross Domain Request withCredentials (Access-Control-Allow-Origin)

做個AJAX跨網域可是容易忘記細節的,這就來篇Note,

後端部分,Server Header請開啟(以PHP動態Header為例):

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");

Cookie夾帶

如需夾帶Cookie則前端的AJAX需開啟Credentials,JQuery為例:

$.ajax({
    xhrFields: {
        withCredentials: true
    },
    type: "GET",
    url: "http://www.example.org/ajax.php"
}).done(function (data) {
    console.log(data);
});

xhrFields中withCredentials要開啟,這就是亮點!

Leave a Reply

Your email address will not be published. Required fields are marked *