-2
bfunc({   
"query": {   
  "count": 1,   
  "created": "2013-05-03T06:20:01Z",   
  "lang": "en-US",   
  "diagnostics": {   
  "publiclyCallable": "true",   
  "cache": {    
    "execution-start-time": "32",   
    "execution-stop-time": "32",   
    "execution-time": "0",   
    "method": "GET",   
    "type": "MEMCACHED",   
    "content": "http://www.vtualerts.com/robots.txt"   
   });

这是我需要使用 javascript 和 jQuery 解析的 JSON 数据。我试着这样做......

<div id="placeholder"></div>    
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>   
<script>   
$.getJSON('myjson.json', function(data) {    
    var output= data.cbfunc.query.count+ "" + data.cbfunc.query.created;     
    document.getElementById("placeholder").innerHTML=output;    
});  

但我收到一个错误

XMLHttpRequest 无法加载 file:///home/shivratna/Desktop/myjson.json。Access-Control-Allow-Origin 不允许 Origin null。

请帮忙。

真诚的感谢

4

2 回答 2

1

它不是有效的 JSON。阅读json.org以了解 JSON 的正确结构。你所拥有的是 JSONP。首先,检查您的 JSON,因为它们没有正确关闭。你缺少右括号。

要将其转换为有效的 JSON,请删除填充函数,如下所示:

{   
  "query": {   
    "count": 1,   
    "created": "2013-05-03T06:20:01Z",   
    "lang": "en-US",   
    "diagnostics": {   
      "publiclyCallable": "true",   
      "cache": {    
        "execution-start-time": "32",   
        "execution-stop-time": "32",   
        "execution-time": "0",   
        "method": "GET",   
        "type": "MEMCACHED",   
        "content": "http://www.vtualerts.com/robots.txt"   
      }
    }
  }
}
于 2013-05-03T07:10:18.990 回答
-1

为什么你使用这样的 json 数据,这是无效的,你可以使用像这样的 json 数据

{ "query": {
"count": 1,
"created": "2013-05-03T06:20:01Z",
"lang": "en-US",
"diagnostics": {
    "publiclyCallable": "true",
    "cache": {
        "execution-start-time": "32",
        "execution-stop-time": "32",
        "execution-time": "0",
        "method": "GET",
        "type": "MEMCACHED",
        "content": "http://www.vtualerts.com/robots.txt"
    }
}
}
}

你的最终代码..

    $.getJSON('myjson.json', function(data) {    
      var output= data.query.count+ "" + data.query.created;     
      document.getElementById("placeholder").innerHTML=output;    
   });  
于 2013-05-03T07:14:38.483 回答