JSONP

JSONP 是一个能够被跨域访问资源的方法。

服务端

server.go

  1. package main
  2. import (
  3. "math/rand"
  4. "net/http"
  5. "time"
  6. "github.com/labstack/echo"
  7. "github.com/labstack/echo/middleware"
  8. )
  9. func main() {
  10. e := echo.New()
  11. e.Use(middleware.Logger())
  12. e.Use(middleware.Recover())
  13. e.Static("/", "public")
  14. // JSONP
  15. e.GET("/jsonp", func(c echo.Context) error {
  16. callback := c.QueryParam("callback")
  17. var content struct {
  18. Response string `json:"response"`
  19. Timestamp time.Time `json:"timestamp"`
  20. Random int `json:"random"`
  21. }
  22. content.Response = "Sent via JSONP"
  23. content.Timestamp = time.Now().UTC()
  24. content.Random = rand.Intn(1000)
  25. return c.JSONP(http.StatusOK, callback, &content)
  26. })
  27. // Start server
  28. e.Logger.Fatal(e.Start(":1323"))
  29. }

客户端

index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  5. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  6. <title>JSONP</title>
  7. <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
  8. <script type="text/javascript">
  9. var host_prefix = 'http://localhost:1323';
  10. $(document).ready(function() {
  11. // JSONP version - add 'callback=?' to the URL - fetch the JSONP response to the request
  12. $("#jsonp-button").click(function(e) {
  13. e.preventDefault();
  14. // The only difference on the client end is the addition of 'callback=?' to the URL
  15. var url = host_prefix + '/jsonp?callback=?';
  16. $.getJSON(url, function(jsonp) {
  17. console.log(jsonp);
  18. $("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
  19. });
  20. });
  21. });
  22. </script>
  23. </head>
  24. <body>
  25. <div class="container" style="margin-top: 50px;">
  26. <input type="button" class="btn btn-primary btn-lg" id="jsonp-button" value="Get JSONP response">
  27. <p>
  28. <pre id="jsonp-response"></pre>
  29. </p>
  30. </div>
  31. </body>
  32. </html>