我可以从java脚本调用Web服务吗?

时间:2009-11-20 10:40:40

标签: javascript

我可以从java脚本调用Web服务吗?

谢谢

4 个答案:

答案 0 :(得分:2)

是的,你可以这样做。

答案 1 :(得分:1)

您可以在与具有正常XHR呼叫的页面相同的服务器上呼叫Web服务。如果服务器位于不同的服务器上,那么您应该使用JSONP调用。注意JSONP没有最好的错误处理。

答案 2 :(得分:1)

您可以轻松调用JSON或RESTful Web服务。

对于SOAP Web服务,您需要library

答案 3 :(得分:1)

当然。我们需要更多信息来了解您正在使用的服务类型以及是否使用JS库。使用Dojo或EXT非常容易。 我将向您展示一个Dojo示例,因为这是我最近的工作。此时我主要将我的服务创建为REST服务。根据服务及其使用方式,我可以将响应作为JSON或JSONP发回。 下面是将响应作为JSONP发送的服务示例,我将其用于跨域调用。您需要使用dojo.io.script.get(如果使用Dojo库):

dojo.io.script.get({
    callbackParamName: 'method',
    url: 'http://mydomain/myservicename/mymethodname/param1/param2',
    timeout: 20000,
    load: dojo.hitch(this,function(response,ioArgs) {
        this.doSomething(response);
    }),
    error: dojo.hitch(this,function(error) {
        alert('uh oh, something went wrong');
    })
});

对于以JSON形式发送响应的服务,您可以使用以下Dojo函数: dojo.xhr,dojo.xhrDelete,dojo.xhrGet,dojo.xhrPost,dojo.xhrPut,dojo.rawXhrPost和dojo.rawXhrPut,具体取决于您所进行的调用类型。以下是一个例子:

dojo.rawXhrPost({
    url: url,
    handleAs: 'json',
    postData: parametersJSON,
    headers: { "Content-Type": "text/json" },
    timeout: 45000,
    //function to be run in case of successful call to the specified Web method
    load: function(data) {
        onComplete(data);
    },
    //function to be run in case of failed call to the specified Web method
    error: function(error) {
        onError(error.message);
    }
});