【问题标题】:Cross domain jquery ajax request with custom headers and request body as JSON string具有自定义标头和请求正文作为 JSON 字符串的跨域 jquery ajax 请求
【发布时间】:2013-02-12 00:04:33
【问题描述】:

我需要从另一个域创建一个 JSON ajax request。在我认为我解决了跨域问题之后,我陷入了困境:

我需要添加我的自定义“myCustomHeader”标头 - 这对于 server 来说很容易,但对于 client 来说似乎要复杂得多...

我们添加了它们

$.ajax({
    type: 'POST',
    data: put the results of your header request here,
    url: 'http://server.com/service',
    beforeSend: function (xhr) { 
        xhr.setRequestHeader('myCustomHeader', '1') 
    },
    success: function(data) {    
        alert('success.');
    }
});

这会生成一个带有我想要的标题的preflight 标题,没有values (CSV),但它们不会出现在request 本身的标题中(如myCustomHeader=X)...

【问题讨论】:

  • 您是否检查过服务器端确实返回了包含“myCustomHeader”的标头 Access-Control-Allow-Headers?
  • 请注意,使用 JSONP 时不能发送自定义标头(以防万一)。
  • 您好,感谢 cmets - 关于 JBL - 不,我正在与 IT 部门核实。 Felix - 没有 jsonp,只是来自 jquery ajax 的标准文本类型,我相信它可以...谢谢!
  • jsonp 是我所知道的唯一跨域方法(代理和 adobe flash 之外)。在没有代理的情况下,您是如何解决跨域问题的?
  • 我刚刚阅读了有关 CORS 的信息,您的服务器是否发送了 Access-Control-Allow-Origin 标头?

标签: javascript jquery ajax preflight


【解决方案1】:

您可以为此目的使用 CORS。

示例代码:

jQuery.support.cors = true; 

function CrosDom_ajax(url) {
        if (window.XDomainRequest
        && $.browser.msie
        && $.browser.version < 10) {
        xdr = new XDomainRequest();
        if (xdr) {
            xdr.onload = function () {
               alert(xdr.responseText);

            };
            xdr.open("get", url);
            xdr.send();
        }
        }
        else {
            $.ajax({
                url: url,
                success: function (response) {


                },
                error: function (data) {
                }
            });
         }
    }

另外你需要在服务器端编写如下代码,以允许跨域访问

Response.AppendHeader("Access-Control-Allow-Origin", "*");           

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-23
    • 2011-07-03
    • 2011-07-05
    • 1970-01-01
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多