[英]Javascript - how to get the manifest json and use it as object?
為什么console.log('Your query count: ' , data);
顯示為空? (即使結果是成功的?調試控制台網絡選項卡顯示數據已成功爬行)
manifest.json的:
{
"title": "API test",
"server": [
{ "agent": "abc",
"url": "def" },
],
}
index.php文件:
<script>
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('http://localhost/manifest.json',
function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
}
else {
var read = JSON.stringify(data);
console.log('Your query count: ' , data);
}
});
</script>
您的代碼適合我,但請嘗試
var read = JSON.stringify(data);
console.log('Your query count: ' , read );
代替
var read = JSON.stringify(data);
console.log('Your query count: ' , data);
編輯:哦,看起來你的manifest.json是不正確的JSON。 嘗試刪除逗號
{
"title": "API test",
"server": [{
"agent": "abc",
"url": "def"
}]
}
你的代碼沒問題。 但是,我注意到你的JSON有一個,
在結束
{
"title": "API test",
"server": [
{ "agent": "abc",
"url": "def" },
],<-- this one
}
只需刪除它,您的代碼就可以運行。 此外,在getJSON的匿名函數的else運算符中,通過read
替換變量data
,您將獲得JSON作為字符串,或者您可以從data
變量中獲取data
。 在這里,您有3種方法可以獲取數據。
var getJSON = function(url, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'json'; xhr.onload = function() { var status = xhr.status; if (status == 200) { callback(null, xhr.response); } else { callback(status); } }; xhr.send(); }; getJSON('https://gist.githubusercontent.com/teocci/3d128c27e37cc5d9b90ade9d68e84ca7/raw/e49f9d765567572aa4119142dc46ea5cc55d9b15/manifest.json%2520', function(err, data) { if (err != null) { alert('Something went wrong: ' + err); } else { var read = JSON.stringify(data); console.log('Your query count: ', read); getInfoA(data); getInfoB(data); getInfoC(data); } }); function getInfoA(jsonData) { var title = jsonData.title; var server = jsonData.server; var agent = server[0].agent; var url = server[0].url; console.log('getInfoA---'); console.log('title: ', title); console.log('agent: ', agent); console.log('url: ', url); } function getInfoB(jsonData) { var title = jsonData.title; var server = jsonData.server; console.log('getInfoB---'); console.log('title: ', title); Object.keys(server).map(function(key, index) { var item = server[key]; var agent = item.agent; var url = item.agent; console.log('agent: ', agent); console.log('url: ', url); }); } function getInfoC(jsonData) { var title = jsonData.title; var server = jsonData.server; console.log('getInfoC---'); console.log('title: ', title); Object.keys(server).forEach(function(key) { var item = server[key]; var agent = item.agent; var url = item.agent; console.log('agent: ', agent); console.log('url: ', url); }); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.