views:

308

answers:

2

So I'm trying to create a C# WCF REST service that is called by jQuery. I've discovered that jQuery requires that AJAX calls are made under the same origin policy. I have a few questions for how I might proceed.

I am already aware of;
1. The hacky solution of JSONP with a server callback
2. The way too much server overhead of having a cross-domain proxy.
3. Using Flash in the browser to make the call and setting up crossdomain.xml at my WCF server root.

I'd rather not use these because;
1. I don't want to use JSON, or at least I don't want to be restricted to using it
2. I would like to separate the server that serves static pages from the one that serves application state.
3. Flash in this day and age is out of the question.

What I'm thinking: is there anything like Flash's crossdomain.xml file that works for jQuery? Is this "same-origin" policy a part of jQuery or is it a restriction in specific browsers? If it's just a part of jQuery, maybe I'll try digging in the code to work around it.

+1  A: 

Unfortunately, the same-origin policy is a restriction of browsers, not explicitly part of jQuery, so I doubt you're going to find a way around that.

I'd suggest your best bet is to stick with the JSONP solution. Yes, you could argue is "hacky", but it's a very widely accepted "hack" for exactly the reasons you're coming up against (i.e. its one of the only feasible options).

As for being restricted to using JSON, if you're in control of both ends of the service call, there's no reason you couldn't use a JSONP style usage pattern, but not actually use JSON... Your server response is just going to be passed to a JavaScript function on the client side, so there's no stopping you from returning, say, XML in a string & then having your callback parse & handle that (although, that's probably pushing you into genuinely "hacky" territory).

Alconja
Fair enough. If its coded into the browser, I guess thats what I'm stuck with.
csauve
see below, this is how to do it. no jsonp. works for xml data and json data
csauve
+1  A: 

You could also consider spitting out an additional http header that will enable cross-domain requests on your web service.

This is described here:

http://www.w3.org/TR/cors/

https://developer.mozilla.org/en/HTTP_access_control

So if you add the following header to any content that your web-service delivers:

Access-Control-Allow-Origin: *

the browser will allow cross-domain requests to that web service. This is supported in most modern browsers (ff 3.5, IE 8, safari 4) and seems to work very nicely for jquery applications hosted at domain foo.com that make ajax calls to bar.com

shreddd
I started using this recently, thanks!
csauve