使用 JSON 传递函数

2016/08/28 后端 推荐 JSON
  本文为「原创」内容,如需转载请注明出处!             
本文共 1107 字,需 13 分钟阅读

  一般来说 JSON 只能是包含基础数据,如果要用回调一般采用的是 JSONP, 但是如果 JSON 也能自带 function 就省去了很多麻烦了。

本文是基于 ASP.NET MVC 利用的 Newtonjson 来进行 JSON 转换和传递的

  • Model 注意这里利用了 JRaw

      public class Person {
          public string Name { get; set; }
          public JRaw Exec { get; set; }
      }
    
  • Controller

     public ActionResult Index()
          {
              Person person = new Person { Name = "Joe",
              Exec = new JRaw("function(){console.log('i am the function')}") };
              ViewBag.Person = JsonConvert.SerializeObject(person);
              return View();
          }
    
  • View

      @{
          Layout = null;
      }
          <!DOCTYPE html>
          <html>
          <head>
              <meta name="viewport" content="width=device-width" />
              <title>Index</title>
              <script>
                  var person = eval(@Html.Raw(@ViewBag.Person));
                  console.log("personJSON",person);
                  person.Exec();
              </script>
          </head>
          <body>
                
          </body>
          </html>
    
    
  • Result

    json-with-function

可以很清楚地看见类型为 JRawExec 传递给 JavaScript 之后就变成了一个可以执行的函数

搜索

    文章目录