Cross-Origin Resource Sharing decsribes interaction between two origins(domains) using headers requests and responses. This blog is useful to understand it.

seen from United States
seen from United States

seen from Italy

seen from United States
seen from United Kingdom
seen from Singapore
seen from United States

seen from Italy
seen from Yemen

seen from Italy
seen from United States
seen from Brazil
seen from Malaysia

seen from Italy

seen from Australia
seen from United Kingdom
seen from Russia
seen from China

seen from Spain

seen from United States
Cross-Origin Resource Sharing decsribes interaction between two origins(domains) using headers requests and responses. This blog is useful to understand it.
javascript - php ajax with json data and cross domain without jquery
Mục đích của cross domain là sử dụng javascript ở website A (ví dụ siteA.com) để gửi request đến site B (ví dụ siteB.com) để trao đổi dữ liệu (GET, POST, PUT, DELETE). Để hoàn thành 1 truy vấn cross-domain cần thoả điều kiện từ cả 2 phía server (php) và client (javascript).
có 2 phương thức để sử dụng cross domain trong javascript
1. JSONP
2. CORS (Cross-Origin Resource Sharing)
tuy nhiên JSONP chỉ hỗ trợ GET method nên bài viết này sẽ chỉ viết về CORS
Để 2 websites có thể trao đổi dữ liệu với nhau thông qua javascript chúng ta cần đảm bảo cả 2 sites có cùng chính sách kết nối (same-origin policy). Với những trình duyệt hỗ trợ CORS chúng ta có thể dễ dàng làm việc này.
Các browsers phổ biến hỗ trợ CORS:
Chrome 3+
Firefox 3.5+
Opera 12+
Safari 4+
Internet Explorer 8+
có thể xem thêm danh sách đầy đủ ở http://caniuse.com/#search=cors
Đầu tiên ta sẽ có hàm javascript đơn giản để khởi tạo kết nối CORS
function initCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; }
Quản lý sự kiện (Event handlers) XMLHttpRequest hỗ trợ các sự kiện sau:
onloadstart* Bắt đầu bắt đầu onprogress Đang xử lý dữ liệu onabort* Khi truy vấn bị huỷ bỏ onerror Truy vấn có lỗi onload Truy vấn thành công ontimeout Truy vấn quá lâu (timeout) onloadend* Truy vấn kết thúc (bao gồm cả thành công và lỗi)
Lưu ý: các events * không được hỗ trợ bởi XDomainRequest (IE browser)
Các tham số header khi thực hiện request
withCredentials mặc đinh, các truy vấn CORS không gửi kèm cookies, vì vậy nếu muốn gửi kèm cookies thì cần đoạn mã sau
xhr.withCredentials = true
Và server cũng phải hỗ trợ
Access-Control-Allow-Credentials: true
php: header(’Access-Control-Allow-Credentials’, true);
Các tham số khác:
Access-Control-Allow-Origin (required) - đây là header bắt buộc phải có ở server. Giá trị của header này là domain của client được phép truy vấn, dùng ký tự * có nghĩa tất cả các domain được phép truy vập.
php: header('Access-Control-Allow-Origin','*'); js: không cần gửi header này
Access-Control-Allow-Methods - server chấp nhận phương thức GET, POST, PUT, DELETE php: header('Access-Control-Allow-Methods','GET,POST'); js: xhr.setRequestHeader(’Access-Control-Request-Methods',’GET,POST');
Access-Control-Request-Headers - tham số header bất kỳ yêu cầu từ client js: setRequestHeader('Access-Control-Request-Headers', 'X-Custom-Header'); Access-Control-Allow-Headers - tham số header hỗ trợ từ server php: header('Access-Control-Allow-Headers','X-Custom-Header');
Request with JSON data để thực hiện truy vấn với json data, cần cấu hình 2 phía (server - client) như sau (các giá trị được ngăn cách bởi dâu phẩy “,” ) php: $this->getResponse()->setHeader('Access-Control-Allow-Headers','Content-Type'); $this->getResponse()->setHeader('Content-type', 'application/json');
js: xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
cấu trúc dữ liệu json gửi từ client cho dữ liệu với dữ liệu {name: dm, age: 20} cần chuyển sang “name=dm&age=20″ vì vậy, cần tự viết 1 hàm để chuyển dữ liệu từ json sang string
Ví dụ đầy đủ để thực hiện truy vấn cross-domain với post json data
javascript
function initCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { // Check if the XMLHttpRequest object has a "withCredentials" property. // "withCredentials" only exists on XMLHTTPRequest2 objects. xhr.open(method, url, true); } else if (typeof XDomainRequest != "undefined") { // Otherwise, check if XDomainRequest. // XDomainRequest only exists in IE, and is IE's way of making CORS requests. xhr = new XDomainRequest(); xhr.open(method, url); } else { // Otherwise, CORS is not supported by the browser. xhr = null; } return xhr; } function makeRequest(method, url){ var xhr = initCORSRequest(method, url); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01'); xhr.setRequestHeader('Access-Control-Request-Headers', 'Content-Type'); //xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); if (!xhr) { console.log('CORS not supported'); return; } // Response handlers. xhr.onload = function() { var returnText = xhr.responseText; var jsonText = JSON.parse(returnText); console.log('Response from CORS request to ' + url, jsonText);
}; xhr.onerror = function() { console.log('Woops, there was an error making the request.'); }; xhr.send("name=dm&age=20"*/); }
makeRequest(’POST’, ‘http://sample-domain.com’);
php
header('Access-Control-Allow-Origin','*'); header('Access-Control-Allow-Headers','Content-Type'); header('Content-type', 'application/json'); header('Access-Control-Allow-Methods','GET,POST'); echo json_encode(array('Response from server' => $_POST));
với jquery chúng ta có thể dễ dàng sử dụng như sau
$.ajax({ url: 'http://sample-domain.com', dataType: 'json', type: 'post', crossDomain: true, jsonp: false, data: {name: 'dm', age: 20}, success: function(rs){ console.log(rs); }, error: function(){ alert('error'); } });
lưu ý, lúc này phía server vẫn phải được cấu hình phù hợp như trên.
tham khảo http://www.html5rocks.com/en/tutorials/cors/
ASync Calls to Dota2/Steam APIs
ASync Calls to Dota2/Steam APIs
Hello folks.
I am currently in process of putting around a Web version of my last app for Dota2 Stats on iOS. BTW, the developing the same using Adobe Flash Buildier 4.7. While building, I notice that there are lot of features that work on a mobile app or a AIR app which actually dont on Web version.
It is actually not the problem with Flash/Adobe but instead it is a standard security issue that…
View On WordPress
Please watch this and understand how serious transgenic dna is.WHAT WILL WE BECOME?
Como activar el cross domain en rails 4
Solo hay que añadir esto al appllication controller
before_filter :cors_preflight_check after_filter :cors_set_access_control_headers
# For all responses in this controller, return the CORS access control headers.
def cors_set_access_control_headers headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' headers['Access-Control-Allow-Headers'] = '*' headers['Access-Control-Max-Age'] = "1728000" end
# If this is a preflight OPTIONS request, then short-circuit the # request, return only the necessary headers and return an empty # text/plain.
def cors_preflight_check if request.method == :options headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS' headers['Access-Control-Allow-Headers'] = '*' headers['Access-Control-Max-Age'] = '1728000' render :text => '', :content_type => 'text/plain' end end
The greatest challenge of our time
I often read things like: climate change is the greatest challenge of our time, poverty is the greatest challenge of our time, cleaning our oceans is the greatest challenge of our time, ... Like it's some kind of competition to win the title of 'Greatest Challenge of Our Time'. This is not very productive and actually creates a kind of behaviour that could be detrimental for solving these problems in the first place.
It's a bit like wanting to build a house and then saying 'the walls are the most important' or 'the foundation is the most important'. They are all important and leaving out any of them or making one of them of inferior quality would have you end up with either no house or a house that is not sturdy enough to be safe enough or at least one that would deteriorate faster than it should.
The same goes with our world problems. What we need to set as a goal is to create a society where everyone can have a good life. Where no one is poor, where there is equality, where everyone can have a life of purpose. Solving poverty, climate change, energy challenges and so forth are like the building blocks we need in order to get there. They are not separate issues competing to be the first one to be tackled though.
Even though with a house you can not add the roof before the walls are set, you can already gather the materials for that roof even before you dig the foundations. It speeds things up once you can start building.
When tackling the problems in our societies we can and should tackle multiple issues at once AND take into consideration the impact of the solution of one issue on other domains. Right now too many solutions are still developed in silos without really thinking about the impact on the bigger system.
Therefore we need to open up our silos and start to have more cross domain, cross disciplinary and cross issue dialogue in order to create this society of tomorrow.
There are, to my knowledge, already two initiatives that have been created from the awareness of this need. One is the New Capacity Building Programme on a European level, the other, which I am part of, is Open Antwerp, which can also be found on Idealist. I'm pretty sure there are more people out there who see this need and more initiatives will be taken. It would be great if we would manage to become aware of each other's existence.
Cross Domain 처리 방법
같은 도메인 그룹 내에 있는 싸이트 간의 cross domain
community.my.com 싸이트와 auth.my.com이라는 싸이트 간에 서로 자유롭게 접근이 되어야 하는 경우 아래와 같이 document.domain을 통해 domain 설정
document.domain = "my.com";
전혀 다른 싸이트간의 cross domain
jsonp : get 방식의 처리 경우에 유효한 방법
postMessage : event 처리 방식
참고: https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
Iframe Auto Height Jquery Plugin
Vakit buldukça uğraştığım, benim de bir jquery pluginim olsun kafasında yapılmış, "Iframe Auto Height" plugin'im artık kullanıma hazır. http://sly777.github.com/Iframe-Height-Jquery-Plugin/ adresinden yükleyebileceğiniz plugin'in özellikleri şunlar;
Iframe'inizde açılan sayfanızın boyuna göre iframe'nizin boyutunu otomatik ayarlıyor.
İsterseniz bazı sayfaları default değerde açabiliyor.
Detaylı değiştirilebilir ayarları mevcut. İster cross-domain'e izin verin, ister bazı sayfaları es geçin, ister debug mod açın. vs. vs. (reklam kokan konuşmalar oldu evet :D)
Cross-Domain destekliyor. (tabii detayları var. Şöyle ki; eğer CD kullanmak istiyorsanız, iframe'de açılan sayfanızdan postmessage fonksiyonunu kullanmanız gerekiyor. Detaylar için tıklayın. )
Debug modu mevcut. Eğer debug modu açarsanız konsolda bütün bilgileri görebiliyorsunuz.
Daha birkaç özellik daha var ancak hepsini tek tek buraya yazmıyorum. Github sayfamda detaylı olarak anlattım bütün özellikleri.
Aslında bir kaç tane iframe plugin'i mevcut ancak projelerimde yeterli gelmediklerinden kendim bir tane hazırladım. Eğer öneriniz, şikayetiniz, yeni özellik isteğiniz veya kodda düzeltmeleriniz olursa çekinmeden belirtin ki kaliteli bir plugin oluşsun ;)
//////////////////////////////////////////// blog.ilkerguller.com by Ilker Guller