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

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


当前回答

保持简单:

跨域: 使用crossDomain: true, 不应该刷新页面: 不,它不会刷新页面,因为当服务器发送回响应时将调用成功或错误异步回调。


示例脚本:

$.ajax({
        type: "POST",
        url: "http://www.yoururl.com/",
        crossDomain: true,
        data: 'param1=value1&param2=value2',
        success: function (data) {
            // do something with server response data
        },
        error: function (err) {
            // handle your error logic here
        }
    });

其他回答

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

检查http://taiyolab.com/mbtweet/scripts/twitterapi_call.js中的post_method函数——这是上面描述的iframe方法的一个很好的例子。

CORS是为你准备的。 CORS是“跨域资源共享”,是一种发送跨域请求的方式。现在XMLHttpRequest2和Fetch API都支持CORS,它可以发送POST和GET请求

但它也有局限性。服务器需要指定Access-Control-Allow-Origin,不能设置为“*”。

如果你想要任何origin都可以发送请求给你,你需要JSONP(也需要设置Access-Control-Allow-Origin,但可以是'*')

对于很多请求方式,如果你不知道如何选择,我认为你需要一个完整的功能组件来做到这一点。让我介绍一个简单的组件https://github.com/Joker-Jelly/catta


如果你正在使用现代浏览器(> IE9, Chrome, FF, Edge等),非常建议你使用一个简单但美丽的组件https://github.com/Joker-Jelly/catta.It没有依赖,小于3KB,它支持Fetch, AJAX和JSONP与相同致命的示例语法和选项。

catta('./data/simple.json').then(function (res) {
  console.log(res);
});

它还支持所有方式导入到您的项目,如ES6模块,CommonJS,甚至HTML中的<script>。

这是一个老问题,但一些新技术可能会帮助人们解决这个问题。

如果你有对其他服务器的管理访问权限,那么你可以使用开源Forge项目来完成你的跨域POST。Forge提供了一个跨域JavaScript XmlHttpRequest包装器,它利用了Flash的原始套接字API。POST甚至可以通过TLS完成。

您需要对您要发布的服务器进行管理访问的原因是,您必须提供一个跨域策略,允许从您的域进行访问。

http://github.com/digitalbazaar/forge

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