Calling a cross-domain .net method from jquery in ie / firefox / chrome

I am trying to call a .NET method (both an asmx file and a regular aspx file) from another domain via jQuery, and I just can't do this work in every browser. At the moment, it works fine in Firefox, but not in IE.

function save() { if (jQuery.browser.msie && window.XDomainRequest) { // Use XDR var params = "{'height':" + 10 + ",'width':" + 10 + ",'pos':'" + 10 + "'}"; var xdr = new XDomainRequest(); xdr.onerror = alert_error; xdr.ontimeout = alert_timeout; xdr.onprogress = alert_progress; xdr.onload = alert_loaded; xdr.timeout = 10000; xdr.open("post", 'http://domain/reciever.asmx/setdata'); //Tried as webservice and as a normal aspx page //xdr.open("post", 'http://domain/default.aspx'); xdr.send(params); } else { var params = "pos=" + positions + "&width=" + screenWidth + "&height=" + screenHeight; var myAjax = new jQuery.ajax( "http://domain/default.aspx", { type: 'post', cache: false, crossDomain: true, data: params }); } } 

At the end of the web.config server has:

 <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> </httpProtocol> 

And web service

 [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string setdata(int width, int height, string pos) 

The aspx page returns:

 Response.Clear(); Response.ContentType = "text/plain"; Response.AddHeader("Access-Control-Allow-Origin", "*"); Response.End(); 

Violinist says: Fiddler detected a protocol violation in session # 2565. Content length mismatch: the request header indicated 38 bytes, but the client sent 0 bytes. Therefore, I believe that this is "Access-Control-Allow-Origin", but I installed it (as far as I know).

Can someone help me understand what I'm doing wrong.

+4
source share
1 answer

Some browsers do not allow cross-domain Ajax calls ( calling using the XmlHttpRequest object ) for some security reasons.

But the solution instead of calls, ajax uses JSONP calls. JSONP avoids this by making the request suitable for the script file. Using JSONP, it is possible to make a cross-domain request,

1. Instead of accessing the XHR object, the browser first creates a new script tag for input into the HTML DOM .

2. The URL of the script tag is set to the URL you are looking to receive / send (using HTTP GET) data.

3. The script tag is entered on the page, calling ...

4. The request is sent to the server, even if it is a cross-domain

5. The server returns data in the form of a JavaScript function call

6. The browser receives data and makes a function call

For implementation details see below URLs

http://www.codeproject.com/Articles/78757/Making-Cross-Domain-jQuery-AJAX-Calls.aspx

http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide

Hope this will definitely help you ...

+1
source

All Articles