[英]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.
我在Web服务上做了一个简单的Echo测试,它将字符串作为参数并将其回显。 I wrote the javascript code that I've been working on in order to access this method here:
我写了我一直在努力的javascript代码,以便在这里访问此方法:
http://jsfiddle.net/stephenbayer/CaHqY/9/ 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. 我真的需要知道,为什么我会收到错误消息,为什么我收到的唯一消息是来自javascript的错误字符串“ Error”。 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. 这是一个通过WCF使用标准SOAP运行的Web服务,并且我们有一个客户端请求通过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. 由于具有相同的起源策略,您无法通过普通AJAX进行跨域调用,因此您需要执行JSONP -Call。
Perhaps you could use CORS but you need to be careful because then youmight be vulnerable to cross site scripting. 也许您可以使用CORS,但需要小心,因为那样的话,您可能会容易受到跨站点脚本的攻击。
Modern browsers prevent cross-domain requests in order to protect users from XSS attacks. 现代浏览器会阻止跨域请求,以保护用户免受XSS攻击。
To handle data coming from another domain, you need one of those 4 solutions : 要处理来自另一个域的数据,您需要以下四种解决方案之一:
Note that the first 2 solutions involve to change the XML server. 请注意,前两个解决方案涉及更改XML服务器。
The others are right. 其他人是对的。 You have to use JSONP instead of JSON.
您必须使用JSONP而不是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. 与其直接将ajax与其他域一起使用,不如将其与您自己的域一起使用,在服务器中创建新的Web服务,例如使用php。
Then, in your php ws you can call the external webservice and it will work. 然后,在您的php ws中,您可以调用外部Web服务,它将起作用。 Use
file_get_contents()
. 使用
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.
您只能对加载javascript的域进行xhr(即ajax)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.