最近項目中需要跨域調用其他項目的數據,其他項目也是使用的EasyUI的datagrid組件,開始以為直接在datagrid的url屬性定義為其他項目的url地址即可,可是測試下發現的確是返回了json數據但是json數據提示“invalid label” 錯誤,網上搜索了下錯誤解決辦法,參考 “JavaScript處理Json的invalid label錯誤解決辦法“的方法利用datagrid的loadData方法加載並轉換了json還是提示上述錯誤,感覺原因不在格式問題。
搜索了下JavaScript跨域調用的文章“JavaScript跨域訪問問題解決方法”得到啟發,發現原來是因為easyUI使用的是JQuery的異步方法加載數據,應該遵循JQuery的跨域訪問規則,也就是上述文章中提到的url中需要加入jsoncallback=?回調函數參數,並且返回的json的格式必須修改為:回調函數名(json數據),而現在返回的數據只是json格式的數據沒有回調函數名,自然提示格式錯誤,於是修改了ASP.NET MVC自定義的JsonResult類,具體如何編寫自定義的JsonResult類見:自定義ASP.NET MVC JsonResult序列化結果,
代碼如下:
public class CustomJsonResult:JsonResult { public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpResponseBase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { #pragma warning disable 0618 //跨域調用需要修改json格式jsoncallback if (context.HttpContext.Request.Params.AllKeys.Contains("jsoncallback")) { String callback = context.HttpContext.Request.Params["jsoncallback"]; response.Write(callback+"("+JsonConvert.SerializeObject(Data)+")"); } else { response.Write(JsonConvert.SerializeObject(Data)); } #pragma warning restore 0618 } } }
EasyUI的datagrid的代碼如下:
//datagrid $('#dg').datagrid({ url:'http://localhost:9000/ManagementSystem/ListCurrent?department=sss&jsoncallback=?', pageNumber: 1, pageSize: 20, pageList: [20, 40, 60, 80, 100], onDblClickRow: function(rowIndex) { edit(); } });