我有以下代码来检索Wikipedia信息框:
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
var url = "https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url, function(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>" + wikiHTML + "</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
} else {
var url = "https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, function(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>" + wikiHTML + "</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
}
});
}
});
}
但是,如果第一个查询失败(由typeof(data.parse) == 'undefined'
检测到true
),则应执行else
子句。问题是,即使在父环境中声明了bnameonly
变量,undefined
变量也是private String workflow_status;
。
答案 0 :(得分:1)
只有在知道响应从服务器返回后(无论是成功还是失败),您才能检查HTML是否为空。你可以在它的jqXHR上使用jQuery的always方法来测试它。
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
function myCallback(data) {
...
}
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url,{data})
.done(myCallback)
.always(function() {
//executed only after $.getJSON succeeds or fails
if ($("#wiki").contents().find('#myinfobox').html() === '') {
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
}
})
}
答案 1 :(得分:0)
根据我在其他论坛(https://forum.jquery.com/topic/how-do-i-access-json-data-outside-of-getjson)找到的答案,我使用回调函数找到了解决方案:
ClassC