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

查看:27
本文介绍了使用 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.

要使用它进行网络服务调用,您只需实例化对象,然后调用它的 open() 方法.我建议这是异步完成的,以保持 UI 响应.当调用 async 时,您将获得对指定的异步方法的回调,该方法将指示请求的状态.当状态为 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天全站免登陆