使用Javascript来使用Web服务 [英] Consuming a Web service using Javascript

查看:140
本文介绍了使用Javascript来使用Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用JavaScript来使用Web服务?我正在寻找一种内置的方法,使用JavaScript框架不是一种选择。

Is there a way to consume a web service using JavaScript? I'm Looking for a built-in way to do it, using a JavaScript framework is not an option.

推荐答案

您可以使用XmlHttpRequest对象本地使用JavaScript来使用Web服务。但是,实例化此对象因浏览器而异。例如,Firefox和IE 7+允许您将其实例化为本机JavaScript对象,但IE6要求您将其实例化为ActiveX控件。

You can consume a web service using JavaScript natively using the XmlHttpRequest object. However instantiating this object varies between browsers. For example Firefox and IE 7+ let you instantiate it as a native JavaScript object but IE6 requires you to instantiate it as an ActiveX control.

因为这个我建议使用诸如jQuery之类的抽象库。如果这不是一个选项,那么将创建抽象为工厂方法并检查浏览器版本。

Because of this I'd recommend using an abstraction library such as jQuery. If that's not an option then abstract the creation into a factory method and check for the browser version.

要使用它来进行Web服务调用,您只需实例化对象和然后调用它的open()方法。我建议这样做是异步的,以保持UI响应。调用异步时,您将获得指定异步方法的回调,该异步方法将指示请求的状态。当状态为4(已加载)时,您可以获取响应数据然后进行处理。

To use this to make a web service call you simply instantiate the object and then call it's open() method. I recommend this is done async to keep the UI responsive. When invoked async you will get callbacks to your specified async method that will indicate the status of the request. When the status is 4 (loaded) you can take the response data and then process it.

如何处理数据将取决于它是什么,如果它是JSON则你可以通过JavaScript的eval()方法运行它,但这确实有一些安全隐患。如果是XML,您可以使用XML DOM来处理它。

How you process the data will depend on what it is, if it's JSON then you can run it through JavaScript's eval() method but that does have some security implications. If it's XML you can use the XML DOM to process it.

参见维基百科,了解有关XMLHttpRequest对象的更多信息。

See Wikipedia for more info on the XMLHttpRequest object.

这篇关于使用Javascript来使用Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆