发布跨域AJAX / XDomainRequest到Web服务 [英] Posting Cross Domain AJAX/XDomainRequest to Web Service

查看:979
本文介绍了发布跨域AJAX / XDomainRequest到Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花费大量的时间,通过在这里的所有的各个岗位和各个其他网站大量阅读,并且具有以下code:

I have spend a LOT of time reading through all the various posts here and on various other websites, and have the following code:

    function post_cors(vars) {
        // cross domain AJAX posting - needs work to function in IE
        var successFunction = vars.success;
        var errorFunction = vars.error;
        var url = vars.url;
        var data = vars.data;

        if ($.browser.msie && window.XDomainRequest) {
            // CROSS DOMAIN AJAX FOR < IE10 (Doesn't work yet!)
            var xdr = new XDomainRequest();
            xdr.open("POST", url);
            xdr.send(JSON.stringify(data));
            xdr.onload = function () {
                // XDomainRequest doesn't provide responseXml, so if you need it:
                alert('Response: ' + xdr.responseText);
            };
        } else {
            $.ajax({ // proper AJAX for sensible browsers
                cache: false,
                dataType: "json",
                url: url,
                crossDomain: true,
                data: data,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data, textStatus, request) {
                    successFunction(data, textStatus, request);
                },
                error: function (data, textStatus, request) {
                    errorFunction(data, textStatus, request);
                }
            });
        };
    };

该函数的调用,如下所示:

The function is called as follows:

post_cors({
    'success': function (data) {
         doStuffWithResponse()
     },
     'url': SOME WEB SERVICE,
     'data': "{ 'para1': '" + para1 + "', 'para2': '" + para2+ "' }"
}); 

该职位标准的跨域的AJAX在后成长起来的浏览器如Chrome和Safari,和完美的作品,包括在iPad等。不过,我不能得到的东西在IE&LT工作; 10。

This posts a standard Cross Domain AJAX post in grown up browsers like Chrome and Safari, and works perfectly, including on iPad etc. However, I cannot get the thing to work in IE < 10.

相关code是:

var xdr = new XDomainRequest();
xdr.open("POST", url);
xdr.send(JSON.stringify(data));

在SO各个线程和其他人认为,这应该工作,这里包括: <一href="http://stackoverflow.com/questions/10442961/how-to-send-json-data-in-xdr-using-the-post-method">How使用POST方法在XDR发送JSON数据

Various threads on SO and others suggest that this SHOULD work, including here: How to send JSON data in XDR using the POST method

但事实并非如此,我想不通为什么,虽然犯罪嫌疑人是做与POST和数据。

But it doesn't, and I can't figure out why, although suspect it is to do with the POST and the Data.

于是,我尝试了各种实验;

So I have tried various experiments;

发布到Web方法不带参数;

<WebMethod()> _
Public Function HelloWorld() As String
    Return "Hello World"
End Function

此出现在本地服务器上运行时的工作,但并不时添加到Web托管服务器。我收到 200 成功code,但似乎并没有能够真正看到响应,既可以通过IE浏览器控制台,或在提琴手。它似乎工作的事实离线可能是一个红色的鲱鱼呢......?

This appears to work when running on local servers, but does not when added to a web hosted server. I receive a 200 success code, but don't seem to be able to actually see the response, either through the IE console, or in Fiddler. The fact that it appears to work "offline" might be a red herring anyway...?

投递到方法,需要参数

<WebMethod()> _
Public Function TryThis(term as string) As String
    Return term
End Function

这总是返回 HTTP 500 错误与IE浏览器,但完全在长大的浏览器。

This ALWAYS returns a http 500 Error with IE, but works perfectly in grown up browsers.

我得到了无论是小提琴或IE浏览器的控制台没有错误的信息。

I get no error information in either Fiddle or IE console.

后显示我这是请求报头:

The latter shows me this as Request Headers:

Key Value
Request POST http://samtest.thinkka.com/api/Sam_ScriptService.asmx/HelloWorld HTTP/1.1
Accept  */*
Origin  http://localhost:63238
Accept-Language en-GB
Accept-Encoding gzip, deflate
User-Agent  Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host    samtest.thinkka.com
Content-Length  108
Proxy-Connection    Keep-Alive
Pragma  no-cache

和响应头:

Key Value
Response    HTTP/1.1 500 Internal Server Error
Cache-Control   private
Content-Type    text/html; charset=utf-8
Server  Microsoft-IIS/7.5
X-AspNet-Version    4.0.30319
X-Powered-By    ASP.NET
Access-Control-Allow-Origin *
Access-Control-Allow-Methods    GET, POST
Access-Control-Allow-Headers    Content-Type
Date    Tue, 08 Oct 2013 10:24:29 GMT
Content-Length  4826

响应体是空的,我不能读取任何错误消息,所以不知道在哪里,为什么这个错误发生。

Response Body is empty, I cannot read any error message so have no idea where or why this error occurs.

我怀疑问题与POST或表单数据所在?

I suspect the issues lies with the POST or with the Form Data?

我试图发送的数据为对象,​​而不是JSON.Stringified,但开不工作,虽然,我不希望它

I have tried posting data as an object, rather than JSON.Stringified, but that does't work, although, I wouldn't expect it to

所有的提琴手,似乎能告诉我,IE浏览器的控制台不会吧:

All that Fiddler seems to be able to tell me that the IE console doesn't it:

No Proxy-Authorization Header is present.
No Authorization Header is present.

无论使用Chrome浏览器,它会返回一个肯定的答复时,出现了验证选项卡下,也出现在提琴手。

Both appear under the "Auth" tab, but also appear in Fiddler when using Chrome, which returns a positive response.

我发现Chrome浏览器的职位数据的两倍,我所有的阅读过程中,我知道这是正确的(虽然不记得为什么在此刻),IE不,它只是做了第一篇文章。我认为这是正确的,但因为它是AJAX的功能?

I notice Chrome posts the data twice, during the course of all my reading I know that this is correct (although can't remember why at the moment), IE doesn't, it's only doing the first post. I think this is correct though as it is a function of AJAX?

我的web.config文件中添加适当的标题:

My Web.Config file adds the proper headers:

<customHeaders>
     <add name="Access-Control-Allow-Origin" value="*" />
     <add name="Access-Control-Allow-Methods" value="GET, POST" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>

很显然,我知道这里的​​跨域问题,并遵循所有的例子我能找到的,但现在我卡...所以在这里发帖。

Obviously, I am aware of the Cross Domain issues here, and have followed all the examples I can find, but I am stuck now... hence posting here.

请不要告诉我不要使用ASMX Web服务,或跨域过帐是不允许的,我现在需要一个解决方案! : - )

Please don't tell me not to use an ASMX web service, or that Cross Domain posting is not allowed, I need a solution now! :-)

在上面贴的链接原来的问题笔者认为,他被发现在他的服务器端的响应错误解决了他的问题,但我的工作完全在一切,除了旧版本的IE(它工作在IE10的方式),所以我看不出它是一个服务器端错误 - 如果是,得到的错误没有信息500 使其无法识别

The author of the original question in the link posted above suggests that he solved his issue by finding an error on his server side response, but mine is working perfectly in everything except older versions of IE (it works in IE10 by the way) so I can't see it being a server side error - and if it is, getting no information on the Error 500 makes it impossible to identify.

推荐答案

首先,你需要修复您的code,因此它不会尝试使用XDomainRequest内IE10,同时支持CORS换XmlHtt prequest和遗留XDomainRequest对象。

First, you need to fix your code so it doesn't try to use XDomainRequest inside IE10, which supports both CORS-for-XmlHttpRequest and the legacy XDomainRequest object.

接下来,你需要更新你的服务器端code,以便它不返回一个HTTP / 500的响应时,该请求缺乏内容类型:应用程序/ JSON 头。 XDomainRequest <一href="http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx"相对=nofollow>不允许你设置的头,你的服务器似乎决定如何解析请求体时所期待的。

Next, you need to update your server-side code so that it doesn't return a HTTP/500 response when the request lacks a Content-Type: application/json header. XDomainRequest doesn't allow you to set that header, and your server appears to be expecting it when deciding how to parse the request body.

这篇关于发布跨域AJAX / XDomainRequest到Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆