• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Jsonp
 

Jsonp

on

  • 233 views

 

Statistics

Views

Total Views
233
Views on SlideShare
233
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Jsonp Jsonp Presentation Transcript

    • JSONP by Jax
    • JSON ( JavaScript Object Notation ) • 一種輕量級的資料交換語言 • 獨立於語言的文字格式 • {"Name": " ", "Id" : 1823, "Rank": 7}
    • JSONP ( JSON with Padding ) • JSON 的一種「使用模式」 • 可以讓網頁從別的網域要資料 <script type="text/javascript" src="http://example.com/RetrieveUser?callback=parseResponse"> </script> parseResponse({"Name": "Cheeso", "Id" : 1823, "Rank": 7})
    • 建立 WebApi 教學網站 Your First ASP.NET Web API • http://www.asp.net/web-api/overview/getting-started-with-aspnet-webapi/tutorial-your-first-web-api
    • 安裝 NuGet 套件 WebApiContrib.Formatting.Jsonp
    • 在 Global.asax.cs 加入 FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration.Formatters);
    • 建立 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)); } }
    • 修改 App_Start/WebApiConfig.cs config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}/{format}", defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional } );
    • 最簡單的呼叫方式 /* 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>
    • 如何使用 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); } });