dmotta
12/20/2013 - 3:27 PM

JavaScript como cliente REST con soporte de CORS (Cross-Origin Resource Sharing).

JavaScript como cliente REST con soporte de CORS (Cross-Origin Resource Sharing).

function createCORSRequest(method, url,data) {
  var xhr = new XMLHttpRequest();      	
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
	//xhr.send(data);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
	//xhr.send(data);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}
// Make the actual CORS request.
function makeCorsRequest(url,data) {
  var xhr = createCORSRequest('POST', url,data);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }
  xhr.onload = function() {
    var responseText = xhr.responseText;
    alert(responseText);   
  };
 
  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };
  xhr.send(data);
}