MVC+JQuery实现跨域Jsonp调用Js
1.MVC控制器
/// <summary> /// 处理Jsonp请求,若没有指定对应的jsoncallback,则返回Json /// </summary> /// <param name="data"></param> /// <returns></returns> private ActionResult Jsonp(object data) { string jsoncallback = Request.QueryString["jsoncallback"]; if (string.IsNullOrEmpty(jsoncallback)) { return Json(data, JsonRequestBehavior.AllowGet); } return Content(string.Format("{0}({1})", jsoncallback, data.ToJson()), "text/plain", System.Text.Encoding.UTF8); } public ActionResult GetTime(string value) { return Jsonp(DateTime.Now + ":" + value); }
2.Javascript
$.ajax({ async: true, url: 'http://localhost/test/gettime', type: 'GET', dataType: 'jsonp', jsonp: 'jsoncallback', data: {value:"abc"}, timeout: 1000, beforeSend: function() { }, success: function(json) { alert(json); }, complete: function(XMLHttpRequest, textStatus) { //alert('complete'); }, error: function(xhr) { //alert("xhr"); } });