javascript 在 Chrome 扩展程序中获取 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11842954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get JSON in a Chrome extension
提问by user1175307
Small problem with my chrome extension.
我的 chrome 扩展程序的小问题。
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.
我只是想从另一台服务器获取一个 JSON 数组。但是清单 2 不允许我这样做。我尝试指定content_security_policy
,但 JSON 数组存储在没有 SSL 证书的服务器上。
So, what should I do without using manifest 1?
那么,如果不使用清单 1,我该怎么办?
回答by Rob W
The CSPcannot 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.
该CSP不能引起你所描述的问题。您很可能使用的是 JSONP 而不是普通的 JSON。JSONP 在 Chrome 中不起作用,因为 JSONP 通过<script>
在文档中插入一个标签来工作,该标签的src
属性设置为 web 服务的 URL。这是 CSP 不允许的。
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:
假设您已在清单文件中设置了正确的权限(例如"permissions": ["http://domain/getjson*"]
,您将始终能够获取和解析 JSON:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var json = xhr.responseText; // Response
json = json.replace(/^[^(]*\(([\S\s]+)\);?$/, ''); // 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();
When using jQuery for ajax, make sure that JSONP is not requested by using jsonp: false
:
将 jQuery 用于 ajax 时,请确保不使用jsonp: false
以下命令请求 JSONP :
$.ajax({url:'...',
jsonp: false ... });
Or, when using $.getJSON
:
或者,当使用$.getJSON
:
$.getJSON('URL which does NOT contain callback=?', ...);