zoukankan      html  css  js  c++  java
  • 跨域Ajax请求(jQuery JSONP MVC)

    通过jQuery的$.ajax方法发送JSONP请求

    js代码

     1     <script type="text/javascript">
     2         function jsonptest2(result) {//jsonptest2必须是全局唯一的方法
     3             alert(result.Age + " " + result.Email);//28 tom@tom.com
     4         }
     5 
     6         $.ajax({
     7             type: "GET",
     8             url: "http://localhost:2528/Default2/JsonAuction/1",//跨域
     9             dataType: "jsonp",
    10             jsonpCallback: "jsonptest2"
    11         });
    12     </script>

    MVC中C#代码,即请求http://localhost:2528/Default2/JsonAuction/1

        public class Default2Controller : Controller
        {
            public ActionResult JsonAuction(int id)
            {
                Person p = new Person() {Age=28,Email="tom@tom.com" };//模拟数据Person类见下面
                return  = new JsonpResult() { Data=p};
            }
        }
      //自定义返回类型
        public class JsonpResult : JsonResult
        {
            public string Callback { get; set; }
            public JsonpResult()
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            }
    
            public override void ExecuteResult(ControllerContext context)
            {
                var httpContext = context.HttpContext;
                var callback = Callback;
                if (string.IsNullOrWhiteSpace(callback))
                {
                    callback = httpContext.Request["callback"];
                }
                httpContext.Response.Write(callback);
                httpContext.Response.Write("(");
                base.ExecuteResult(context);
                httpContext.Response.Write(");");
    
            }
        }
    
    
        public class Person
        {
            public int Age
            {
                get;
                set;
            }
            public string Email
            {
                get;
                set;
            }
            
        }
  • 相关阅读:
    初识Django-前后端不分离(一)
    虚拟环境的搭建
    python+request+Excel做接口自动化测试(二)
    使用postman+newman+python做接口自动化测试
    如何处理接口响应结果分析
    request使用的封装
    python中unittest的使用
    使用python的接口测试环境搭建及使用
    关于测试流程的指导心得
    Redis 学习
  • 原文地址:https://www.cnblogs.com/jesselzj/p/3532597.html
Copyright © 2011-2022 走看看