在Chrome扩展程序中获取JSON

use*_*307 9 javascript ajax json google-chrome-extension content-security-policy

我的chrome扩展程序存在小问题.

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

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

Rob*_*b W 14

CSP不能引起你所描述的问题.您很可能使用的是JSONP而不是普通的JSON.JSONP在Chrome中不起作用,因为JSONP的工作原理是<script>在文档中插入一个标记,该标记的src属性设置为webservice的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();
Run Code Online (Sandbox Code Playgroud)

使用jQuery for ajax时,请确保使用jsonp: false以下命令不要求JSONP :

$.ajax({url:'...',
        jsonp: false ... });
Run Code Online (Sandbox Code Playgroud)

或者,使用时$.getJSON:

$.getJSON('URL which does NOT contain callback=?', ...);
Run Code Online (Sandbox Code Playgroud)