I have a JSON WCF service and I have written some javascript to access the service like this,
function stuffClick2() {
$.ajax({
url: "http://192.168.54.98/JsonWCFService/Service1.svc/Post",
type: "POST",
contentType: "application/json",
data: '{"x":"1","y":"2","message":"The answer is: "}',
dataType: "html",
success: function(data) { $('body').html(data); }
});
}
I have written an HTML page which has the above javascript in it. The HTML page is served up using IIS.
When I access the HTML page using chrome on my PC I see these operations being sent to the WCF JSON service in this order,
OPTIONS /JsonWCFService/Service1.svc/Post HTTP/1.1
POST /JsonWCFService/Service1.svc/Post HTTP/1.1
The OPTIONS was previously failing, but I made the OPTIONS call return this header which then makes it work,
Access-Control-Allow-Origin: *
But the callback I have defined above does not work,
success: function(data) { $('body').html(data); }
I know that the WCF service has returned something like this,
<b> The answer is 3 </b>
But when the callback is called the value of data is an empty string.
When I run the html page in a different browser (IE) which only causes a POST call, but not an OPTIONS call then it works. I notice that IE warns me that it poses a security risk and asks me whether I want to continue.
I ran across this issue when I was trying to implement CORS with WCF for a mobile HTML app I was making. OPTIONS is a preflight request to see if a method is available before calling it.
Here will be your problems:
Im not sure if you are using CORS or not, but the principal will be the same, as it sends a OPTIONS request then a POST request.
Thanks your answer did put me on a path of solving the problem.
When I was accessing the HTML page with the ajax javascript in it I was using,
http://localhost/file.html
But if you look at the javascript it is accessing the WCF service using,
http://192.168.54.98/JsonWCFService/Service1.svc/Post
If I make them both
http://mymachinename.domain.com/JsonWCFService/Service1.svc/Post
http://mymachinename.domain.com/file.html
Then it works without having to call an OPTIONS operation.
That doesn't explain why an OPTIONS and then a POST from chrome doesn't work. Chrome just seems to ignore the results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With