简体   繁体   中英

How do I get jQuery to pull xml from webservice

I've been trying to get data from

http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=GBP

I want to be able to use jQuery to extract the data, I've tried $.ajax and even :

$.get('http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=USD&ToCurrency=GBP', function(data) {
    console.log(data);
});

It works fine in my browser (firefox) as a url, however fails in jQuery. How can I extract the currency rate from the web service using jQuery without it throwing up an error?

Due to the same origin policy restriction that is built into browsers you cannot send AJAX requests to different domains than the one that hosted the page containing this javascript (which I suspect is not http://www.webservicex.net ). To workaround this issue you could write a server side script on your domain that will act as a bridge between your domain and the distant domain and then send an AJAX request to your script:

$.get('/myscript?FromCurrency=USD&ToCurrency=GBP', function(data) {
    console.log(data);
});

The server side script will simply take the two query string parameters and send them as HTTP request to the remote domain and return the results. The way to implement this script will of course depend on the server side language you are using.

Another approach is to use JSONP but this only works if the remote domain supports it. If it doesn't you need a server side bridge.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM