Requirements: domain a. test.com to Ajax request B. General handler under test.com
1. Front-End AJAX requests: (Domain name a.test. com)
$.ajax ({dataType:"Jsonp", data: {"Ajaxmethod": "Getusergamesign", "Cookieid": Cookieid}, Jsonp:"Jsonp_callback",//server-side receive, for function name, arbitrarily definedURL: '/httpb. Test.com/ajax/usergamesign.ashx ',//request addresses for different domain namesSuccess: _callback,//You can also write function (Result) {...};Errorfunction() {alert (' Server Internal Error! ‘); }});var_callback =function(Result) {//result is the returned value: {"code": 0, "msg": "IB"}if(Result! =NULL) { if(Result.code = = 0) {alert (result.msg); }}};
Other parameters:
// or postasync:false// I tried not to sync the effect
2. Server side:(under domain name b.test. com)
Public classUsergamesign:basecommon, IHttpHandler { Public voidProcessRequest (HttpContext context) {Try { if(!string. IsNullOrEmpty (context. request["Ajaxmethod"])) { stringResponseText =""; Context. Response.ContentType="Text/plain"; stringAjaxmethod = context. request["Ajaxmethod"]. ToLower (); Switch(ajaxmethod) { Case "getusergamesign": ResponseText= This. Getusergamesign (context); Break; default: Break; } context. Response.Write (ResponseText); //results returned: {"code": 0, "msg": "IB"}context. Response.End (); } } Catch(Exception ex) //resolve this error: Thread was being aborted. explanation of the problem >> {if(! (ex isSystem.Threading.ThreadAbortException)) {context. Response.Write (ex. Message); Context. Response.End (); } } } /// <summary> ///Get user Tags/// </summary> /// <param name= "context" ></param> /// <returns></returns> Public stringGetusergamesign (HttpContext context) {stringCookieidstr = context. request["Cookieid"]; stringStrformat ="{{\ "code\": {0},\ "msg\": \ "{1}\"}}"; //Determine if the Jsonp method is requested stringJSONP =string. Empty; if(!string. IsNullOrEmpty (httpcontext.current.request["Jsonp_callback"]) {JSONP= Context. request["Jsonp_callback"]; Context. Response.ContentType="Text/javascript"; } User User=NewUser (); stringUserProperty =user. Getuseproperty (Cookieid); if(!string. IsNullOrEmpty (UserProperty)) {if(string. IsNullOrEmpty (JSONP)) {return string. Format (Strformat,0, UserProperty);//normal form return } Else {
The return format of the//JSONP type : Jsonp ({"Code": 0, "msg": "IB"}) as a parameter of the front-end Ajax callback function returnJsonp +"("+string. Format (Strformat,0, UserProperty) +")"; } } Else { return string. Format (Strformat,-1,"failed"); } } }
Outside the station read:
jquery uses Jsonp for cross-domain calls
Jsonp detailed
Ajax and JSONP are not matter read in detail
Talk about JSON and JSONP, and maybe you'll be enlightened.
Ajax cross-domain requests