1

I have a web service with this form:

http://<remote_domain_ip>/api/v1/search/?query=the_query

Which results a JSON document in response.

How do I create/compose a JQuery JSON/ajax call so I can get the response back?

Reponse is in form:

{
"status_code":200,
"status_txt":"OK",
"field1":"abc",
"field2":"some_text"
}
quarks
  • 33,478
  • 73
  • 290
  • 513

2 Answers2

1

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.

Community
  • 1
  • 1
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
-1

You can't, assuming is not the same domain you're on. If you have access to remote_domain_ip, or can get them to host a file for you, you can use EasyXDM. There are similar work-around tools involving Flash you can try. Otherwise, you'll need to perform the request on the back end.

morgancodes
  • 25,055
  • 38
  • 135
  • 187