简体   繁体   中英

Comsuming RESTful service in javascript

I am trying to consume my newly setup RESTful WCF service, located at

[http://196.34.92.60/api/api/v1/public.svc/getoperators]

I accessed it using some third party tools, which I grabbed from

http://code.google.com/a/eclipselabs.org/p/restclient-tool/

https://addons.mozilla.org/en-US/firefox/addon/restclient/

and my results look like I expected:

{
   "Results":
   [
       "golden arrow",
       "jammie",
       "myciti"
   ]
}

All fine and well. When I just type the url into my web browser, the response is

<ResultList xmlns="http://schemas.datacontract.org/2004/07/Developer_Portal"xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Results xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><a:string>golden arrow</a:string><a:string>jammie</a:string><a:string>myciti</a:string></Results></ResultList>

Not what I expected, but I assumed this was normal, and tried to comsume service in Javascript (here is fiddle)

http://jsfiddle.net/JmTe4/11/

It responds with an error. At this point I'm stumped: what do I need to do to get the desired response in javascript?

Couple of things. Some of which were already mentioned by other members.

  1. AJAX calls via XMLHttpRequest will not work across domains. In other words, your AJAX code cannot call 196.34.92.60 from jsfiddle.net. They are different domains.
  2. Your browser is returning XML since it is sending "Accepts: text\\html" as a header. jQuery will resolve this issue as it uses application\\json in the request (unless you specify otherwise).

So issue 2 is already fixed. Issue 1 can be resolved by using JSONP. You should just need to add ?callback=? to the end of your url. However, read through the documentation on jQuery's site for a full overview.

Go to this URL and search the page for "JSONP" http://api.jquery.com/jQuery.getJSON/

The problem was in the server webconfig. I had to add

<binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />

Thanks for your suggestions guys, they probably solved some other problems I would have come across anyway. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM