Posting Cross Domain AJAX/XDomainRequest to Web Se

2019-07-15 10:20发布

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+ "' }"
}); 

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.

The relevant code is:

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

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

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;

Posting to a Web Method with no parameters;

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

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...?

Posting to a Method which takes parameters

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

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

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

And Response Headers:

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.

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

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

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.

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

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?

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.

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! :-)

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.

2条回答
该账号已被封号
2楼-- · 2019-07-15 10:35

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.

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.

查看更多
趁早两清
3楼-- · 2019-07-15 10:42

This my be a bit out of date, but I've found that IE8 actually sends the POST data in a binary stream (or maybe just plain text). I was having problems trying to decode the form POST when I found this out. A quick one-liner in ASP.NET C# to get this content is this:

string strContent = new System.Text.ASCIIEncoding().GetString(Context.Request.BinaryRead((int)Context.Request.InputStream.Length));

Expand on this to your heart's content.

查看更多
登录 后发表回答