Avatar ·

为什么Google要在JSON响应前加上while(1);?

大家好!我是一名前端开发新手,最近在使用Google API时遇到了一个有趣的特性。当我向某些端点(如Google Calendar API或Google Suggest)发送请求时,响应中会在JSON之前出现一个奇怪的构造:`while(1);`。 以下是响应示例: ``` while(1); {"items": [{"id": 1, "name": "test"}]} ``` 起初我以为这是某种错误或bug。尝试通过`JSON.parse()`解析这样的响应——自然得到了错误,因为`while(1);`不是有效的JSON。 我不得不写一个hack来去掉这个前缀: ```javascript fetch('https://some-google-api.com/data') .then(response => response.text()) .then(text => { const json = text.replace(/^while\(1\);/, ''); const data = JSON.parse(json); console.log(data); }); ``` 但这看起来非常奇怪且不直观。为什么Google要添加这个`while(1);`呢?毕竟这