Chrome扩展:远程api并解析接收到的JSON数据

Chrome Extension: remote api and parse the received JSON data

本文关键字:数据 JSON 扩展 远程 api Chrome      更新时间:2023-09-26

我正在做一个chrome扩展,它调用远程API,我需要读取JSON数据,但它无法解析数据?Jquery应该包含在manifest属性的"background:"中吗?如果是,如何?"http://ajax.googleapis.com/ajax/libs/lquery/1.11.0/jquery.min.js"

manifest.json

{
  "manifest_version": 8,
  "name": "Getting started example",
  "description": "This extension shows a Google Image search result for the current page",
  "version": "1.0",
  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "p",
    "default_popup": "popup.html"
  },
    "background": {
    "scripts": ["background.js"]
  },
    "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": [ "myscript.js"]
    }
  ],
  "icons": {
      "64":"icon.png"
      },
  "permissions": [
      "http://domain.com/*"
    ]
}

background.js

   var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://domain.com/api/path", false);
    xhr.send();
            var result = xhr.responseText;
           //var result = eval('(' + xhr.responseText + ')');
    alert(result);//work print json data
    alert(result.results[1].url);// does not work

收到json数据

{"results":[
{"name":"Academic","url":"http:'/'/www.rapidintellect.com'/AEQweb'/"},{"name":"Academy","url":"http:'/'/aocrj.org'/"}
]} {"results":[
{"name2":"Academic","url":"http:'/'/www.rapidintellect.com'/AEQweb'/"},{"name2":"Academy","url":"http:'/'/aocrj.org'/"}
]}

您可以使用JSON.parse函数将JSON解析为JavaScript中的Object

var result = JSON.parse(xhr.responseText);
alert(result.results[0].url);

不过,我不确定您最初的Ajax请求是否有效。

考虑到您使用jquery标记了这个问题,我们可以简化Ajax请求,并自动解析JSON:

$.ajax({
  type: 'GET',
  url: 'http://example.com/...',
  dataType: 'json',
}).success(function(result){
  alert(result.results[1].url)
});

或者,由于这是一个简单的GET请求,您可以使用更简单的方法:

$.getJSON('http://example.com/...', function(result){
  alert(result.results[1].url)
});