如何通过JavaScript发送跨域POST请求?
注释-它不应该刷新页面,然后我需要抓取并解析响应。
如何通过JavaScript发送跨域POST请求?
注释-它不应该刷新页面,然后我需要抓取并解析响应。
当前回答
应该可以用YQL自定义表+ JS XHR,看看: http://developer.yahoo.com/yql/guide/index.html
我用它来做一些客户端(js) html抓取,工作很好 (我有一个完整的音频播放器,搜索互联网/播放列表/歌词/最后调频信息,所有客户端js + YQL)
其他回答
创建一个iFrame, 在里面放入一个隐藏输入的表单, 将表单的动作设置为URL, 向文档中添加iframe 提交表格
伪代码
var ifr = document.createElement('iframe');
var frm = document.createElement('form');
frm.setAttribute("action", "yoururl");
frm.setAttribute("method", "post");
// create hidden inputs, add them
// not shown, but similar (create, setAttribute, appendChild)
ifr.appendChild(frm);
document.body.appendChild(ifr);
frm.submit();
你可能想样式iframe,隐藏和绝对定位。不确定跨站点发布将被浏览器允许,但如果是这样,这是如何做到的。
如果您可以访问所有相关的服务器,请在另一个域请求的页面的回复标题中放入以下内容:
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;
}
这可能会产生安全问题,您应该确保采取了适当的措施来验证请求。
如果你可以访问跨域服务器,并且不想在服务器端做任何代码更改,你可以使用一个名为“xdomain”的库。
工作原理:
步骤1: 服务器1:包含xdomain库,并将跨域配置为从域:
<script src="js/xdomain.min.js" slave="https://crossdomain_server/proxy.html"></script>
步骤2: 在跨域服务器上,创建一个proxy.html文件,并将服务器1作为主服务器:
proxy.html:
<!DOCTYPE HTML>
<script src="js/xdomain.min.js"></script>
<script>
xdomain.masters({
"https://server1" : '*'
});
</script>
步骤3:
现在,您可以从server1对proxy.html作为端点进行AJAX调用。这是绕过CORS请求。图书馆内部使用iframe解决方案,它与凭证和所有可能的方法一起工作:GET, POST等。
查询ajax代码:
$.ajax({
url: 'https://crossdomain_server/proxy.html',
type: "POST",
data: JSON.stringify(_data),
dataType: "json",
contentType: "application/json; charset=utf-8"
})
.done(_success)
.fail(_failed)
这是一个老问题,但一些新技术可能会帮助人们解决这个问题。
如果你有对其他服务器的管理访问权限,那么你可以使用开源Forge项目来完成你的跨域POST。Forge提供了一个跨域JavaScript XmlHttpRequest包装器,它利用了Flash的原始套接字API。POST甚至可以通过TLS完成。
您需要对您要发布的服务器进行管理访问的原因是,您必须提供一个跨域策略,允许从您的域进行访问。
http://github.com/digitalbazaar/forge
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差异),获得响应,并返回您想要的任何内容。