如何通过JavaScript发送跨域POST请求?
注释-它不应该刷新页面,然后我需要抓取并解析响应。
如何通过JavaScript发送跨域POST请求?
注释-它不应该刷新页面,然后我需要抓取并解析响应。
当前回答
如果您可以访问所有相关的服务器,请在另一个域请求的页面的回复标题中放入以下内容:
PHP:
header('Access-Control-Allow-Origin: *');
例如,在Drupal的xmlrpc.php代码中,你会这样做:
function xmlrpc_server_output($xml) {
$xml = '<?xml version="1.0"?>'."\n". $xml;
header('Connection: close');
header('Content-Length: '. strlen($xml));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Date: '. date('r'));
// $xml = str_replace("\n", " ", $xml);
echo $xml;
exit;
}
这可能会产生安全问题,您应该确保采取了适当的措施来验证请求。
其他回答
Create two hidden iframes (add "display: none;" to the css style). Make your second iframe point to something on your own domain. Create a hidden form, set its method to "post" with target = your first iframe, and optionally set enctype to "multipart/form-data" (I'm thinking you want to do POST because you want to send multipart data like pictures?) When ready, make the form submit() the POST. If you can get the other domain to return javascript that will do Cross-Domain Communication With Iframes (http://softwareas.com/cross-domain-communication-with-iframes) then you are in luck, and you can capture the response as well.
当然,如果您想使用您的服务器作为代理,您可以避免所有这些。只需将表单提交到您自己的服务器,该服务器将把请求代理到另一个服务器(假设另一个服务器没有设置为注意到IP差异),获得响应,并返回您想要的任何内容。
如果您可以访问所有相关的服务器,请在另一个域请求的页面的回复标题中放入以下内容:
PHP:
header('Access-Control-Allow-Origin: *');
例如,在Drupal的xmlrpc.php代码中,你会这样做:
function xmlrpc_server_output($xml) {
$xml = '<?xml version="1.0"?>'."\n". $xml;
header('Connection: close');
header('Content-Length: '. strlen($xml));
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/x-www-form-urlencoded');
header('Date: '. date('r'));
// $xml = str_replace("\n", " ", $xml);
echo $xml;
exit;
}
这可能会产生安全问题,您应该确保采取了适当的措施来验证请求。
这是一个老问题,但一些新技术可能会帮助人们解决这个问题。
如果你有对其他服务器的管理访问权限,那么你可以使用开源Forge项目来完成你的跨域POST。Forge提供了一个跨域JavaScript XmlHttpRequest包装器,它利用了Flash的原始套接字API。POST甚至可以通过TLS完成。
您需要对您要发布的服务器进行管理访问的原因是,您必须提供一个跨域策略,允许从您的域进行访问。
http://github.com/digitalbazaar/forge
还有一件重要的事情要注意!! 在上面的例子中描述了如何使用
$.ajax({
type : 'POST',
dataType : 'json',
url : 'another-remote-server',
...
});
JQuery 1.6及以下版本在跨域XHR方面有一个bug。 根据Firebug,除了OPTIONS之外,没有其他请求发送。没有职位。在所有。
花了5个小时测试/调优我的代码。在远程服务器(脚本)上添加大量的头文件。没有任何效果。 但后来,我将JQuery lib更新到1.6.4,一切都很顺利。
检查http://taiyolab.com/mbtweet/scripts/twitterapi_call.js中的post_method函数——这是上面描述的iframe方法的一个很好的例子。