【问题标题】:Submit form via ajax to another domain通过ajax提交表单到另一个域
【发布时间】:2013-02-07 22:25:31
【问题描述】:

我需要通过 ajax(不是 json)向另一个域提交表单,但不断收到错误

XMLHttpRequest cannot load http://some.other.domain/. Origin http://localhost:8081 is not allowed by Access-Control-Allow-Origin.

有没有办法“解决”这个问题?

$.ajax({
    type: "POST",
    dataType: "text/html",
    data: $("#surveyForm").serialize(),
    crossDomain: true,
    url: "http://some.other.domain",
    processData: false,
    error: function (jqXHR, textStatus, errorThrown) {
    },
    success: function (response) {
    }
});

【问题讨论】:

  • 您拥有其他域吗?如果是这样,您可以将 CORS 标头添加到响应中:html5rocks.com/en/tutorials/cors
  • 很遗憾,我不拥有另一个域。

标签: jquery cors


【解决方案1】:

您最好的选择可能是设置proxy server。你不能使用 JSON-P,因为你正在做一个表单 POST,你不能使用 CORS,因为你不控制远程域上的 headers。

【讨论】:

  • 是的,我认为这可能是我最好的选择。
【解决方案2】:

我认为要向跨域发送数据,您必须使用 JSONP 数据类型。你不能发布整个表格。我下面的代码对我来说是正确的(希望这对你有帮助)

  $.ajax({ url: "MYURL",
    data: {
           paxMessage: JSON.stringify(paxMessage)
          },

    contentType: "application/json; charset=utf-8",

    dataType: "jsonp",

    success: function(data) {
              alert("Data Submitted successfully");
           },

    error: function(XMLHttpRequest, textStatus, errorThrown) {
           alert(textStatus);
           }
       });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 2016-08-20
    • 2011-04-21
    相关资源
    最近更新 更多