标签:style blog http color io os 使用 ar java
需求:域名a.test.com要ajax请求b.test.com下的一般处理程序
1.前端Ajax请求:(域名a.test.com下的)
$.ajax({ dataType: "jsonp", data: { "ajaxMethod": "getusergamesign", "cookieid": cookieid }, jsonp: "jsonp_callback", //服务器端接收,用于function名,随便定义 url: ‘http://b.test.com/Ajax/UserGameSign.ashx‘, //请求不同域名的地址 success: _callBack, //也可以写function(result) {...}; error: function() { alert(‘服务器内部错误!‘); } }); var _callBack = function(result) { //result为返回的值:{"code":0,"msg":"IB"} if (result != null) { if (result.code == 0) { alert(result.msg); } } };
其他参数:
type : "get", //或post async:false, //我试了没起到同步的效果
2.服务器端:(域名b.test.com下的)
public class UserGameSign : BaseCommon, IHttpHandler { public void ProcessRequest(HttpContext context) { try { if (!string.IsNullOrEmpty(context.Request["ajaxMethod"])) { string responseText = ""; context.Response.ContentType = "text/plain"; string ajaxMethod = context.Request["ajaxMethod"].ToLower(); switch (ajaxMethod) { case "getusergamesign": responseText = this.GetUserGameSign(context); break; default: break; } context.Response.Write(responseText); //返回的结果:{"code":0,"msg":"IB"} context.Response.End(); } } catch (Exception ex) //解决此错误:Thread was being aborted. 问题详解>> { if (!(ex is System.Threading.ThreadAbortException)) { context.Response.Write(ex.Message); context.Response.End(); } } } /// <summary> /// 获取用户标签 /// </summary> /// <param name="context"></param> /// <returns></returns> public string GetUserGameSign(HttpContext context) { string cookieIdstr = context.Request["cookieid"]; string strFormat = "{{\"code\":{0},\"msg\":\"{1}\"}}"; //判断是否是jsonp方式请求 string jsonp = string.Empty; if (!string.IsNullOrEmpty(HttpContext.Current.Request["jsonp_callback"])) { jsonp = context.Request["jsonp_callback"]; context.Response.ContentType = "text/javascript"; } User user = new User(); string userProperty = user.GetUseProperty(cookieId); if (!string.IsNullOrEmpty(userProperty)) { if (string.IsNullOrEmpty(jsonp)) { return string.Format(strFormat, 0, userProperty); //正常形式返回 } else {
//jsonp类型的返回 格式:jsonp({"code":0,"msg":"IB"}) 作为前端ajax回调函数的参数 return jsonp + "(" + string.Format(strFormat, 0, userProperty) + ")"; } } else { return string.Format(strFormat, -1, "失败"); } } }
站外扩展阅读:
标签:style blog http color io os 使用 ar java
原文地址:http://www.cnblogs.com/zxx193/p/4029185.html