cors.html 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>CORS test</title>
  5. <style>
  6. html,body{font:normal 1em arial,helvetica;}
  7. </style>
  8. <script> // http://www.html5rocks.com/en/tutorials/cors/
  9. // Create the XHR object.
  10. function createCORSRequest(method, url) {
  11. var xhr = new XMLHttpRequest();
  12. if ("withCredentials" in xhr) {
  13. // XHR for Chrome/Firefox/Opera/Safari.
  14. xhr.open(method, url, true);
  15. } else if (typeof XDomainRequest != "undefined") {
  16. // XDomainRequest for IE.
  17. xhr = new XDomainRequest();
  18. xhr.open(method, url);
  19. } else {
  20. // CORS not supported.
  21. xhr = null;
  22. }
  23. return xhr;
  24. }
  25. // Helper method to parse the title tag from the response.
  26. function getTitle(text) {
  27. return text.match('<title>(.*)?</title>')[1];
  28. }
  29. // Make the actual CORS request.
  30. function makeCorsRequest() {
  31. var url = "http://localhost/cors.reply.html";
  32. var xhr = createCORSRequest('GET', url);
  33. if (!xhr) {
  34. alert('CORS not supported');
  35. return;
  36. }
  37. // Response handlers.
  38. xhr.onload = function() {
  39. var text = xhr.responseText;
  40. var title = getTitle(text);
  41. alert('Response from CORS request to ' + url + ': ' + title);
  42. };
  43. xhr.onerror = function() {
  44. alert('Woops, there was an error making the request.');
  45. };
  46. xhr.send();
  47. }
  48. function start() {}
  49. </script>
  50. </head>
  51. <body onload="start()">
  52. <h1>Cross-origin resource sharing test</h1>
  53. <button onclick="makeCorsRequest()">Run CORS request</button>
  54. <p>More information on CORS: See <a href="http://enable-cors.org/">enable-cors.org</a> and <a href="http://www.html5rocks.com/en/tutorials/cors/">html5rocks.com</a>.</p>
  55. </body>
  56. </html>