[英]How do I call a web service from javascript
Say I have a web service http://www.example.com/webservice.pl?q=google which returns text "google.com". 假设我有一个Web服务http://www.example.com/webservice.pl?q=google ,它返回文本“google.com”。 I need to call this web service ( http://www.example.com/webservice.pl ) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.
我需要从带有参数(q = google)的JavaScript模块调用此Web服务( http://www.example.com/webservice.pl ),然后使用返回值(“google.com”)进一步执行此操作处理。
What's the simplest way to do this? 最简单的方法是什么? I am a total JavaScript newbie, so any help is much appreciated.
我是一个完整的JavaScript新手,所以任何帮助都非常感谢。
EDIT: 编辑:
It has been a decade since I answered this question and we now have support for cross-domain XHR in the form of CORS . 自从我回答这个问题已经十年了,我们现在支持CORS形式的跨域XHR。
For any modern app consider using fetch to make your requests. 对于任何现代应用程序,请考虑使用fetch来发出请求。 If you need support for older browsers you can add a polyfill .
如果您需要支持旧版浏览器,可以添加polyfill 。
Original answer: 原始答案:
Keep in mind that you cannot make requests across domains. 请注意,您无法跨域提出请求。 For example, if your page is on yourexample.com and the web service is on myexample.com you cannot make a request to it directly.
例如,如果您的网页位于yourexample.com,并且网络服务位于myexample.com上,则您无法直接向其发出请求。
If you do need to make a request like this then you will need to set up a proxy on your server. 如果您确实需要提出这样的请求,那么您需要在服务器上设置代理。 You would make a request to that proxy page, and it will retrieve the data from the web service and return it to your page.
您将向该代理页面发出请求,它将从Web服务检索数据并将其返回到您的页面。
Take a look at one of the many javascript libraries out there. 看看那里的众多JavaScript库之一。 I'd recommend jQuery , personally.
我个人推荐jQuery 。 Aside from all the fancy UI stuff they can do, it has really good cross-browser AJAX libraries .
除了他们可以做的所有花哨的UI内容之外,它还有非常好的跨浏览器AJAX库 。
$.get(
"http://xyz.com/webservice.pl",
{ q : "google" },
function(data) {
alert(data); // "google.com"
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.