在 Chrome 扩展程序中获取 JSON [英] Get JSON in a Chrome extension
问题描述
我的 chrome 扩展程序的小问题.
Small problem with my chrome extension.
我只是想从另一台服务器获取一个 JSON 数组.但是清单 2 不允许我这样做.我尝试指定 content_security_policy
,但 JSON 数组存储在没有 SSL 证书的服务器上.
I just wanted to get a JSON array from another server. But manifest 2 doesn't allow me to do it. I tried specify content_security_policy
, but the JSON array is stored on a server without SSL cert.
那么,如果不使用清单 1,我该怎么办?
So, what should I do without using manifest 1?
推荐答案
CSP 不能导致你描述的问题.您很可能使用的是 JSONP 而不是普通的 JSON.JSONP 在 Chrome 中不起作用,因为 JSONP 通过在文档中插入 标签来工作,其
src
属性设置为网络服务的 URL.这是 CSP 不允许的.
The CSP cannot cause the problem you've described. It's very likely that you're using JSONP instead of plain JSON. JSONP does not work in Chrome, because JSONP works by inserting a <script>
tag in the document, whose src
attribute is set to the URL of the webservice. This is disallowed by the CSP.
如果您在清单文件中设置了正确的权限(例如 "permissions": ["http://domain/getjson*"]
,您将始终能够获得和解析 JSON:
Provided that you've set the correct permission in the manifest file (e.g. "permissions": ["http://domain/getjson*"]
, you will always be able to get and parse the JSON:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var json = xhr.responseText; // Response
json = json.replace(/^[^(]*(([Ss]+));?$/, '$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 for ajax 时,确保没有使用 jsonp: false
:
When using jQuery for ajax, make sure that JSONP is not requested by using jsonp: false
:
$.ajax({url:'...',
jsonp: false ... });
或者,当使用 $.getJSON
时:>
$.getJSON('URL which does NOT contain callback=?', ...);
这篇关于在 Chrome 扩展程序中获取 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!