一、JSONP(JSON with Padding)
客户端:
function TestJsonp() {
$.ajax({
type: "GET",
url: "http://localhost/MVC/Books/JsonpTest",
dataType: "JSONP",
jsonpCallback: "ExecJsonpCallback"
})
}
function ExecJsonpCallback(obj) {
alert(obj.Name);
}
服务端:
public class JsonpResult : JsonResult
{
public JsonpResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}
public override void ExecuteResult(ControllerContext context)
{
var httpContext = context.HttpContext;
string callback = context.HttpContext.Request["callback"];
httpContext.Response.Write(callback + "(");
base.ExecuteResult(context);
httpContext.Response.Write(");");
}
}
public class BooksController : Controller
{
public ActionResult JsonpTest()
{
return new JsonpResult { Data = new { Name = "JSONP" } };
}
}
要点:1.Ajax不能直接取得返回,通过回调函数获得结果;
2.所有的JSONP请求必须是GET请求,MVC默认拒绝AJAX的GET请求,所以需设置JsonRequestBehavior.AllowGet
3.这是不安全的方式,不要用于敏感信息发送
来源:https://www.cnblogs.com/jskenson/p/11083390.html