Ajax跨域请求
需求:域名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, "失败"); } } }
解法方案的问题:详细>>
script请求返回JSON实际上是脚本注入。
1.不能设置同步调用(默认异步)
2.不能接受HTTP状态码
3.不能使用POST提交(默认GET)
4.不能发送和接受HTTP头
站外扩展阅读: