简体   繁体   中英

JQuery accessing remote site with $.ajax()

I broke this down to the absolute simplest code that will not work. I made a simple Echo Test on my webservice that will take a string as a parameter and echo it back. I wrote the javascript code that I've been working on in order to access this method here:

http://jsfiddle.net/stephenbayer/CaHqY/9/

I really need to know, why I am getting an error, and why the only message I'm getting back is the error string "Error" from javascript. How do I fix this and get this working.

This is a web service that has been running using standard SOAP through WCF, and we had a client that requested access through javascript. Sounded crazy to me, but I didn't think it would be that difficult. I can not find any good clear information about getting these cross-domain calls to work at all.

You can't do a Cross-Domain Call via normal AJAX due to the Same Origin Policy, you need to do a JSONP -Call for that.

Perhaps you could use CORS but you need to be careful because then youmight be vulnerable to cross site scripting.

Modern browsers prevent cross-domain requests in order to protect users from XSS attacks.

To handle data coming from another domain, you need one of those 4 solutions :

  • modified headers on the xml server side
  • jsonp request and response
  • a proxy so that your browser thinks that both domains are the same
  • relaxed protection in the browser (not possible on all of them)

Note that the first 2 solutions involve to change the XML server.

The others are right. You have to use JSONP instead of JSON.

But there are an alternative:

Instead of using the ajax direct with the other domain, use it with your own domain, creating a new webservice in your server, using php for example.

Then, in your php ws you can call the external webservice and it will work. Use file_get_contents() .

I use it to get addresses codes using a public server:

$remote_data = @file_get_contents('http://republicavirtual.com.br/web_cep.php?formato=json&cep='.urlencode($_REQUEST['cep']));

echo $remote_data;

Your browser is stopping the request because of the same origin policy . You can only make an xhr (ie ajax) to the domain from where the javascript was loaded.

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