开发者

Can i call web service from java script?

Can i Call web service开发者_JAVA技巧 from java script?

Thanks


Yes, you can do this.


Definitely. We would need a bit more information to know what kind of service you are using and if you are using a JS library. This is very easy with Dojo or EXT. I'll show you a Dojo example as that is what I'm working with the most lately. I mostly create my services as REST services at this point. Depending on the service and how it's going to be used, I either send the response back as JSON or JSONP. Below is an example for services that send the response as JSONP, which I use for cross-domain calls. You would need to use dojo.io.script.get (if using the Dojo library):

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');
    })
});

For services that send the response back as JSON, you can use the following Dojo functions: dojo.xhr, dojo.xhrDelete, dojo.xhrGet, dojo.xhrPost, dojo.xhrPut, dojo.rawXhrPost, and dojo.rawXhrPut depending on the type of call you make. Below is an example:

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);
    }
});


You can call a webservice on the same server as the page with a normal XHR call. If the server is on a different server then you should use a JSONP call. NOTE the JSONP doesnt have the best error handling.


You can easily call a JSON or a RESTful web service.

For SOAP web services you need a library.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜