简体   繁体   English

没有回调的JSONP如何工作?

[英]How is this JSONP without a callback working?

I'm using a client-side SDK, which creates a script under the hood and attaches it to the <head> , and looks like the following: 我使用的是客户端SDK,该SDK在后台创建脚本并将其附加到<head> ,如下所示:

<script src="http://foo.com?foo=bar"></script>

Notice that there's no callback parameter. 请注意,没有callback参数。

The response sends back the following (with header Content-Type: application/javascript ): 响应发送回以下内容(带有标头Content-Type: application/javascript ):

{ document.cookie="something=thing" }

And it sets the cookie in the browser (I can see when I look at the cookies in the dev tools). 并在浏览器中设置cookie(在开发工具中查看cookie时可以看到)。

The strange this is, in the URL of the script, there's no callback parameter, as you would normally expect in a JSONP request. 奇怪的是,在脚本的URL中没有回调参数,就像通常在JSONP请求中期望的那样。

I tried to replicate this behavior by adding a similar script to a local web page and am hitting a local server that returns the same response, but it doesn't set a cookie, unlike the SDK. 我试图通过向本地网页添加类似的脚本并点击返回相同响应的本地服务器来复制此行为,但与SDK不同的是,它没有设置cookie。 The SDK itself is pretty simple and I don't see any other magic happening. SDK本身非常简单,我看不到发生任何其他魔术。

Has anyone seen anything like this before? 有人看过这样的东西吗? How does it work? 它是如何工作的?

Edit: here is the internal SDK method and sample response 编辑:这是内部SDK方法和示例响应

    _jsonp: function(o, e) {
        var t = document.createElement("script");
        t.type = "text/javascript", t.src = e, t.async = !0, document.getElementsByTagName("head")[0].appendChild(t), o.log("SENT JSONP request: " + e)
    },

Sample response: 样本回复:

Response headers 响应头

Connection: keep-alive
Content-Encoding: gzip
Content-Length: 158
Content-Type: application/javascript

Response body 反应体

{document.cookie=<redacted>}

Despite the method name in the API source code, it isn't JSONP. 尽管API源代码中有方法名称,但它不是JSONP。

JSONP is a JavaScript program which conforms to the specific format of: Contains only a function call, with one argument, which would be JSON if it was taken out of the JavaScript program and put in a JSON file. JSONP是一种JavaScript程序,符合以下特定格式:仅包含带有一个参数的函数调用,如果将其从JavaScript程序中取出并放入JSON文件,则该参数为JSON。

JSONP works by injecting a <script> element which loads and executes the JavaScript program. JSONP通过注入<script>元素来工作,该元素加载并执行JavaScript程序。

What you have here is a JavaScript program that doesn't conform to the JSONP format. 您在这里拥有的是一个不符合JSONP格式的JavaScript程序。

It is still a JavaScript program. 它仍然是一个JavaScript程序。

Loading with a <script> still works. 使用<script>加载仍然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM