需求:域名a.test.com要ajax請求b.test.com下的通常處理程序javascript
1.前端Ajax請求:(域名a.test.com下的)html
$.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下的)java
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, "失敗"); } } }
解法方案的問題:詳細>>jquery
script請求返回JSON其實是腳本注入。
1.不能設置同步調用(默認異步)
2.不能接受HTTP狀態碼
3.不能使用POST提交(默認GET)
4.不能發送和接受HTTP頭ajax
站外擴展閱讀:json
jsonp詳解服務器
ajax 和jsonp 不是一碼事 細讀詳解 cookie