.net MVC下跨域Ajax请求(JSONP)
发布时间:2020-12-16 02:45:07 所属栏目:百科 来源:网络整理
导读:一、JSONP(JSON with Padding) 客户端: script type="text/javascript" function TestJsonp() { $.ajax({ type: "GET",url: "http://localhost/MVC/Books/JsonpTest",dataType: "JSONP",jsonpCallback: "ExecJsonpCallback" }) } function ExecJsonpCallb
|
一、JSONP(JSON with Padding) 客户端: <script type="text/javascript">
function TestJsonp() {
$.ajax({
type: "GET",url: "http://localhost/MVC/Books/JsonpTest",dataType: "JSONP",jsonpCallback: "ExecJsonpCallback"
})
}
function ExecJsonpCallback(obj) {
alert(obj.Name);
}
</script>
服务端: 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.这是不安全的方式,不要用于敏感信息发送 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
