It depends. If you are say on domain a.com
and your web service is also located at the same place, then you can simply do it this way:
$.ajax('path-to-your-service/WebMethodName', data, function(r){
// Success callback, you have your answer in r.d object
}, function(e){
// Error callback
});
However, if you are on say b.com
and the web service is located on a.com
, then you are limited by a concept called Same-Domain Policy. In other words, you can't use AJAX calls (or XMLHttpRequest) to fetch data from that web service, unless you follow certain rules. One is to use Access-Control-Allow-Origin HTTP Header field, which has some cross-browser issues. Another way could be to use JSONP, which requires the server to support it.
To use JSONP, you should use jQuery's $.getJSON()
method, and provide a callback query string key alongside your parameters sent via HTTP GET.
$.getJSON('path-to-your-service?x=some&y=thing?callback?', function(r){
// Success callback. Your JSON object would be the r parameter
});
I recommend that you use JSONP, if you are the creator of the web service, and if you use .NET framework, I also recommend that you simply use a Generic Handler instead of a web service, since we had many problems configuring web service. However, in your server code, you should check the incoming GET request for a query string key called callback, and if it exists, you should wrap your returning JSON inside a function this way:
callback({
a: a1,
b: b1,
c: c1
});
Understanding JSONP (the concept and the way it occurs) is very crucial. Without a deep understanding, your future maintenance would be a huge burden. I suggest reading this question.