9

我的 chrome 扩展的小问题。

我只是想从另一台服务器获取一个 JSON 数组。但是清单 2 不允许我这样做。我试过指定content_security_policy,但 JSON 数组存储在没有 SSL 证书的服务器上。

那么,如果不使用清单 1,我该怎么办?

4

1 回答 1

15

CSP不会导致您描述的问题。您很可能使用的是 JSONP 而不是纯 JSON。JSONP 在 Chrome 中不起作用,因为 JSONP 通过<script>在文档中插入一个标签来工​​作,该标签的src属性设置为 web 服务的 URL。CSP 不允许这样做

前提是您在清单文件中设置了正确的权限(例如"permissions": ["http://domain/getjson*"],您将始终能够获取和解析 JSON:

var xhr = new XMLHttpRequest();
xhr.onload = function() {
    var json = xhr.responseText;                         // Response
    json = json.replace(/^[^(]*\(([\S\s]+)\);?$/, '$1'); // Turn JSONP in JSON
    json = JSON.parse(json);                             // Parse JSON
    // ... enjoy your parsed json...
};
// Example:
data = 'Example: appended to the query string..';
xhr.open('GET', 'http://domain/getjson?data=' + encodeURIComponent(data));
xhr.send();

将 jQuery 用于 ajax 时,请确保未使用以下命令请求 JSONP jsonp: false

$.ajax({url:'...',
        jsonp: false ... });

或者,使用时$.getJSON

$.getJSON('URL which does NOT contain callback=?', ...);
于 2012-08-07T12:07:49.307 回答