Jsonp

409 views
297 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
409
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
2
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Jsonp

  1. 1. JSONP by Jax
  2. 2. JSON ( JavaScript Object Notation ) • 一種輕量級的資料交換語言 • 獨立於語言的文字格式 • {"Name": " ", "Id" : 1823, "Rank": 7}
  3. 3. JSONP ( JSON with Padding ) • JSON 的一種「使用模式」 • 可以讓網頁從別的網域要資料 <script type="text/javascript" src="http://example.com/RetrieveUser?callback=parseResponse"> </script> parseResponse({"Name": "Cheeso", "Id" : 1823, "Rank": 7})
  4. 4. 建立 WebApi 教學網站 Your First ASP.NET Web API • http://www.asp.net/web-api/overview/getting-started-with-aspnet-webapi/tutorial-your-first-web-api
  5. 5. 安裝 NuGet 套件 WebApiContrib.Formatting.Jsonp
  6. 6. 在 Global.asax.cs 加入 FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration.Formatters);
  7. 7. 建立 App_Start/FormatterConfig.cs public class FormatterConfig { public static void RegisterFormatters(MediaTypeFormatterCollection formatters) { formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; // Insert the JSONP formatter in front of the standard JSON formatter. formatters.Insert(0, new JsonpMediaTypeFormatter(formatters.JsonFormatter)); } }
  8. 8. 修改 App_Start/WebApiConfig.cs config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}/{format}", defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional } );
  9. 9. 最簡單的呼叫方式 /* functionCall({"Name": "Cheeso", "Id" : 1823, "Rank": 7}) */ <script type="text/javascript"> function functionCall(data){ console.log(data); } </script> <script type="text/javascript" src="/api/products/2?callback=functionCall"></script>
  10. 10. 如何使用 jQuery 連接 $.getJSON("/api/products/2?callback=?", function (data) { console.log(data); }); $.ajax({ type: "get", url: "/api/products/2", dataType: "jsonp", jsonp: "callback", success: function (data) { console.log(data); } });

×