如何从 jQuery 调用 Web 服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/861784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:56:58  来源:igfitidea点击:

How to call a web service from jQuery

jqueryweb-services

提问by Jalpesh Vadgama

I want to call a webservice from jQuery. How can I do that?

我想从 jQuery 调用网络服务。我怎样才能做到这一点?

回答by

You can make an AJAX request like any other requests:

您可以像任何其他请求一样发出 AJAX 请求:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})

回答by John G

EDIT:

编辑:

The OP was not looking to use cross-domain requests, but jQuery supports JSONP as of v1.5. See jQuery.ajax(), specificically the crossDomainparameter.

OP 并不打算使用跨域请求,但 jQuery 从 v1.5 开始支持 JSONP。请参阅jQuery.ajax(),特别是crossDomain参数。

The regular jQuery Ajax requests will not work cross-site, so if you want to query a remote RESTful web service, you'll probably have to make a proxy on your server and query that with a jQuery get request. See this sitefor an example.

常规的 jQuery Ajax 请求无法跨站点工作,因此如果您想查询远程 RESTful Web 服务,您可能必须在服务器上创建一个代理并使用 jQuery get 请求进行查询。有关示例,请参阅此站点

If it's a SOAP web service, you may want to try the jqSOAPClient plugin.

如果它是 SOAP Web 服务,您可能想尝试jqSOAPClient 插件

回答by poeticGeek

I blogged about how to consume a WCF service using jQuery:

我写了一篇关于如何使用 jQuery 使用 WCF 服务的博客:

http://yoavniran.wordpress.com/2009/08/02/creating-a-webservice-proxy-with-jquery/

http://yoavniran.wordpress.com/2009/08/02/creating-a-webservice-proxy-with-jquery/

The post shows how to create a service proxy straight up in javascript.

这篇文章展示了如何直接在 javascript 中创建服务代理。

回答by Rob Cartlidge

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

如果按照 Marwan Aouida 的回答,人们有像我这样的问题......代码有一个小错字。而不是“成功”,它说“成功”改变拼写,代码工作正常。

回答by Frank Taylor

In Java, this return value fails with jQuery Ajax GET:

在 Java 中,此返回值会因 jQuery Ajax GET 而失败:

return Response.status(200).entity(pojoObj).build();

But this works:

但这有效:

ResponseBuilder rb = Response.status(200).entity(pojoObj);
return rb.header("Access-Control-Allow-Origin", "*").build();

----

Full class:

全班:

@Path("/password")
public class PasswordStorage {
    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    public Response getRole() {
        Contact pojoObj= new Contact();
        pojoObj.setRole("manager");

        ResponseBuilder rb = Response.status(200).entity(pojoObj);
        return rb.header("Access-Control-Allow-Origin", "*").build();

        //Fails jQuery: return Response.status(200).entity(pojoObj).build();
    }
}