javascript - Calling cross-domain .net-method from jquery in ie/firefox/chrome -
i have been trying call .net method (both asmx file , normal aspx file) domain through jquery , can't job done in every browser. @ moment works fine in firefox 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 webservice , 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 }); } } on server end web.config has:
<httpprotocol> <customheaders> <add name="access-control-allow-origin" value="*" /> </customheaders> </httpprotocol> and webservice
[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(); fiddler says: fiddler has detected protocol violation in session #2565. content-length mismatch: request header indicated 38 bytes, client sent 0 bytes. believe "access-control-allow-origin" have set (to knowledge @ least).
can me understand doing wrong.
some browsers not allow cross-domain ajax calls (a call using xmlhttprequest object) security reasons.
but solution is instead of ajax calls use jsonp calls. jsonp avoids making request suitable script file. using jsonp following things happen make cross-domain request possible,
1.instead of accessing xhr object, browser first creates new script tag inject html dom.
2.the script tag's url set url you're looking get/post(using http get) data to.
3.the script tag injected page, causing...
4.the request sent server, if it's cross-domain
5.the server returns data in form of javascript function call
6.the browser receives data , executes function call
see urls below implementation details,
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 helps you...
Comments
Post a Comment