How do I call a web service from javascript

后端 未结 2 792
闹比i
闹比i 2020-12-14 04:08

Say I have a web service http://www.example.com/webservice.pl?q=google which returns text \"google.com\". I need to call this web service (http://www.example.com/webservice.

相关标签:
2条回答
  • 2020-12-14 04:39

    Take a look at one of the many javascript libraries out there. I'd recommend jQuery, personally. Aside from all the fancy UI stuff they can do, it has really good cross-browser AJAX libraries.

    $.get(
        "http://xyz.com/webservice.pl",
        { q : "google" },
        function(data) {
            alert(data);  // "google.com"
        }
    );
    
    0 讨论(0)
  • 2020-12-14 04:42

    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.

    For any modern app consider using fetch to make your requests. If you need support for older browsers you can add a 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.

    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.

    0 讨论(0)
提交回复
热议问题