views:

124

answers:

1

I've set up Cross-Origin Resource Sharing on a server (Jetty using the CrossOriginFilter) and it works perfectly on IE8 and Firefox. On Chrome, it just ... doesn't.

  $.ajax({ url : crossOriginURL,
    type : "GET",
    error : function(req, message) {
        alert(message);
    },
    dataType :  "json" } );

The error function is invoked, with the helpful message "error". It seems to be making the request, but without any of the headers you'd expect. If the URL is from the same origin, it works fine.

+1  A: 

I have solved my problem this way:

Add this to your PHP Code:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

Or add these headers to your response.

Problem: The browsers ask to the server for options before your main request, to check if the site has the option to allow comunication with different origin, and then if yes, they do your POST or GET request.

EDIT: Try this (without your hack) to see if you're receiving data...

$.ajax({ url : crossOriginURL,
    type : "GET",
    error : function(req, message) {
        alert(message);
    },
    success : function(data) {
        alert(data);
    },
    dataType :  "text"} );
CuSS
can you mark as right answer please?
CuSS
Actually, what finally worked for me is xhr.setRequestHeader('Content-Type', 'text/plain');
Malvolio
In that case, can you post your own answer and mark THAT as the correct one? (I don't have this particular problem, but I do like to keep the list of unanswered questions clean)
ssokolow
my answer works to all browsers. You don't need to request custom headers because who restricts or not the page is server and browser engine... if you were receiving a blank response, problaly it was bad dataType on ajax, that happens because you didn't choose the right dataType. Read about dataType in http://api.jquery.com/jQuery.ajax/ . in ajax options array place the {dataType:"text"}
CuSS