跳转到内容

JSONP

JSONP(JSON with Padding)是一种在不支持 CORS 的旧版浏览器中进行跨域请求的技术。它通过将 JSON 响应包装在 JavaScript 函数调用中来工作。浏览器通过 <script> 标签加载响应(不受同源策略限制),包装函数会以数据作为参数执行。

当你调用 c.JSONP() 时,Gin 会检查 callback 查询参数。如果存在,响应体将被包装为 callbackName({"foo":"bar"})Content-Typeapplication/javascript。如果没有提供 callback,响应的行为与标准的 c.JSON() 调用相同。

package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/JSONP", func(c *gin.Context) {
data := map[string]interface{}{
"foo": "bar",
}
// The callback name is read from the query string, e.g.:
// GET /JSONP?callback=x
// Will output : x({\"foo\":\"bar\"})
c.JSONP(http.StatusOK, data)
})
// Listen and serve on 0.0.0.0:8080
router.Run(":8080")
}

使用 curl 测试以查看 JSONP 和普通 JSON 响应的区别:

Terminal window
# With callback -- returns JavaScript
curl "http://localhost:8080/JSONP?callback=handleData"
# Output: handleData({"foo":"bar"});
# Without callback -- returns plain JSON
curl "http://localhost:8080/JSONP"
# Output: {"foo":"bar"}

另请参阅