Reading JSON through JQuery from Cross Domain ASP.NET Web Service
Recently I had an issue with JQuery and accessing JSON from a cross domain ASP.NET Web Service. After much googling, I stumbled upon many articles that provided no fix that would solve the issue.
Every sample I found was some derivative of the following code:
$.ajax({ type: 'POST', dataType: 'jsonp', contentType: "application/json; charset=utf-8", , url: 'http://www.domain.com/webservice.asmx/function', data: '{}', success: function (response) {} });
Nearly every post pointing out that the contentType argument was the issue but it still didn’t work when I included it. There were posts that said you can’t use GET and had to use POST. There might be valid security issues with not using GET but that’s another topic of discussion. in the case of an open web service where you’re providing raw data to be consumed, a GET should suffice just fine.
To support GET, you need to add the following attribute tags to your asmx.cs:
[sourcecode language=”csharp”][WebMethod(), ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)][/sourcecode]
This will cause ASP.NET to automatically serialize the returned data to JSON without requiring you to do it manually in code. There are no issues when making the call locally either. The second you go cross domain, the call fails.
A few articles mention JSONP (JSON with Padding) which is supposed to provide a workaround for the Same Origin Policy in JavaScript. Once I implemented the JSONP, the entire function
function getJSON() { var url = 'http://www.domain.com/webservice.asmx/function'; $.ajax({ type: 'GET', url: url, async: false, jsonpCallback: 'jsonCallback', contentType: "application/json", dataType: 'jsonp', success: function (json) { alert(json); }, error: function (e) { alert(e.toString()); } }); }