我在使用Json的HTML页面中显示了SPARQL查询的结果,我的问题是当输入某个值并且查询没有显示结果时它应该显示一个警告框。我的代码如下:
HTML
<table id="results">
</table>
查询脚本
var query = [
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX yago: <http://dbpedia.org/class/yago/>",
"PREFIX type: <http://dbpedia.org/class/yago/>",
"PREFIX prop: <http://dbpedia.org/property/>",
"SELECT ?name ?runtime",
"WHERE {",
"?film rdf:type dbo:Film.",
"?film dbp:name ?name.",
"?film dbo:director dbr:Peter_Jackson.",
"} GROUP BY ?name ?runtime"
].join(" ");
alert("this query: [" + query + "]");
var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
console.log(queryUrl);
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function (data) {
console.log(data);
// get the table element
var table = $("#results");
// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;
// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);
// grab the actual results from the data.
var bindings = data.results.bindings;
// for each result, make a table row and add it to the table.
for (rowIdx in bindings) {
table.append(getTableRow(headerVars, bindings[rowIdx]));
}
if (bindings.trim().length == 0) {
alert("empty"); //IF BINDING IS EMPTY DISPLAY ALERT BOX
}
}
});
目前,如果bindings
为空,则不显示任何内容,只显示trHeaders
。
如果bindings
为空或<td>
为空,如何弹出提醒框?
希望这个问题得到理解。谢谢你的时间。
答案 0 :(得分:2)
您可以通过以下几种方式执行此操作:
如果bindings
是对象的常量,但有时可能为空:
if (data.results.bindings.length) {
//exists
} else {
alert('goes here');
}
如果并非始终在服务器的响应中设置bindings
:
if (data.results.hasOwnProperty('bindings')) {
//exists
} else {
alert('goes here');
}