我有这个我想用 Javascript 解析的 json 响应。
[{"video_source_id":100,"title":"YouTube Top Rated"},
{"video_source_id":101,"title":"YouTube Top Favorites"}]
我是 Java Script、JSON 的新手。在网页中解析和显示它的最佳方式是什么?
这是我所拥有的,但我收到以下错误
TypeError:无法读取未定义的属性“0”
在行中
document.getElementById("video_source_id").innerHTML = jsonObj.video_source_id[i];
完整代码:
function loadJSON()
{
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Safari
http_request = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var data_file = "/vcaWS/api/sources";
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
for(var i=0;i<jsonObj.length;i++){
document.getElementById("video_source_id").innerHTML = jsonObj.video_source_id[i];
}
}
}
http_request.open("GET", data_file, true);
http_request.send();
}