如何通过JavaScript发送跨域POST请求?

注释-它不应该刷新页面,然后我需要抓取并解析响应。


当前回答

如果你可以访问跨域服务器,并且不想在服务器端做任何代码更改,你可以使用一个名为“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)

其他回答

创建一个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,隐藏和绝对定位。不确定跨站点发布将被浏览器允许,但如果是这样,这是如何做到的。

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差异),获得响应,并返回您想要的任何内容。

还有一件重要的事情要注意!! 在上面的例子中描述了如何使用

$.ajax({
    type     : 'POST',
    dataType : 'json', 
    url      : 'another-remote-server',
    ...
});

JQuery 1.6及以下版本在跨域XHR方面有一个bug。 根据Firebug,除了OPTIONS之外,没有其他请求发送。没有职位。在所有。

花了5个小时测试/调优我的代码。在远程服务器(脚本)上添加大量的头文件。没有任何效果。 但后来,我将JQuery lib更新到1.6.4,一切都很顺利。

应该可以用YQL自定义表+ JS XHR,看看: http://developer.yahoo.com/yql/guide/index.html

我用它来做一些客户端(js) html抓取,工作很好 (我有一个完整的音频播放器,搜索互联网/播放列表/歌词/最后调频信息,所有客户端js + YQL)

高水平……您需要在服务器上设置cname,以便other-ser.your-server.com指向other-server.com。

您的页面动态地创建了一个不可见的iframe,它充当您到other-server.com的传输。然后,您必须通过JS从您的页面与other-server.com通信,并使用回调将数据返回到您的页面。

可能,但需要your-server.com和other-server.com的协调