Search code examples
ajaxmamp

AJAX Cross Origin Error


I'm trying to set up my first AJAX dev site on MAMP. The image below shows my file structure inside a folder htdocs/javascriptAJAX/

enter image description here

The code in my app.js file is :

(function(){

var request = new XMLHttpRequest();
request.open('GET', '/data.txt');
request.onreadystatechange = function() {
  if ((request.readyState===4) && (request.status===200)) {
    console.log(request);
  }
}
request.send();

})();

When i look in my console though, I'm getting the standard denial because of cross-origin requests:

XMLHttpRequest cannot load file:///data.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

How do I correct this? Surely if this is being run on MAMP it would have the same server?

Many thanks,

Emily


Solution

  • This problem was caused by the trailing forward slash in the .open() method.

    Removing it solved the problem.