开发者

Consuming Web Services by AJAX directly

I'm currently developing a web-site f开发者_JAVA技巧or the public transportation system based on the Trafikanten API (http://reis.trafikanten.no/topp2009/topp2009ws.asmx)

The site has several functionalities though it's Web-Services. It is implemented done in .NET framework with SOAP format. But we need to consume it's functionalities in client side language like JavaScript to be able to display the information in web-page. Can anybody suggest some easy way to cope this scenario?


Provided you're using a LAMP stack:

I would write a PHP script using the nusoap (http://sourceforge.net/projects/nusoap/) libarary to consume the SOAP web service and return JSON to your JavaScript via an AJAX call.

Edit

It's even easier in .NET. Just right click on your project and choose Add a web service. Then you can access methods of the web service just as you would any other object. As far as using it in JS, you could implement create an ASP page that outputs the results in JSON format and then consume that using jQuery as you would with a LAMP stack. Although, with the post back abilities of ASP, you might be better off letting it do the heavy lifting in JS and consume the web services directly in your code file behind your view.

Hope that helps.


If the service doesn't support JSONP, which it probably doesn't as an ASMX service, you'll need to create a service proxy to run on your local web server. Then, use that local service to act as an intermediary that circumvents the browser's cross-domain limitation.

If you added a service reference to Top2009WS in your ASP.NET project, something like this could act as a server-side proxy for GetLines() for example:

[WebMethod]
public Line[] GetLines(int ID) {
  var client = new Topp2009WS.Topp2009WSSoapClient();

  client.open();

  return client.GetLines(ID);
}

Then, you could call through the proxy like this on the client-side:

$.ajax({
  url: 'Service.asmx/GetLines',
  type: 'POST',
  dataType: 'json',
  contentType: 'application/json',
  data: '{"ID":' + 12345 + '}',
  success: function(response) {
    // Alerts the first result's "LineName"
    alert(response.d[0].LineName);
  }
});

See this post for more information on using jQuery to call the web service.


I've done it in the past as Jesse says but with .NET. I build an "composed service" or adapter service which then calls the other services. The composed service would communicate SOAP with the .NET services while your application would communicate JSON with your composed service.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜