做個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要開啟,這就是亮點!