无法在Javascript中加载要在控制台上打印的JSON数据

时间:2017-02-28 11:17:02

标签: javascript json jsp d3.js

我正在尝试在控制台日志上打印JSON数据

这里我的目的是在控制台中打印json数据,该数据存在于relevence.json文件中

但它不起作用,请帮帮我

在我的jsp文件中

<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="static/js/donut.js"></script>

和我的donut.js是

function loadJSON(callback) {

var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'relevancy.json', true);
xobj.onreadystatechange = function() {
    if (xobj.readyState == 4 && xobj.status == "200") {

        // .open will NOT return a value but simply returns undefined in async mode so use a callback
        callback(xobj.responseText);

    }
}
xobj.send(null);
}

// Call to function with anonymous callback
loadJSON(function(response) {
    // Do Something with the response e.g.
    jsonresponse = JSON.parse(response);

    // Assuming json data is wrapped in square brackets as Drew suggests
   console.log(jsonresponse[0].relevance);
});

我的json文件是

[
 {"created_by":null, 
   "created_date":null,
  "last_update_date":null,
   "relevance":100,
   "search_keyword":"unable login",
   "solution_description":"unable to login into clarity application",
   "solution_id":1,
   "technology":"Claims"
   }
]

控制台上没有打印任何内容

1 个答案:

答案 0 :(得分:0)

观察:

  • 验证response对象。是JSON Object还是JSON String。如果是JSON字符串,那么您必须使用JSON.parse(response)

var jsonObj = [{
	"created_by": null,
	"created_date": null,
	"last_update_date": null,
	"relevance": 100,
	"search_keyword": "unable login",
	"solution_description": "unable to login into clarity application",
	"solution_id": 1,
	"technology": "Claims"
}];

console.log(jsonObj[0].relevance);